【发布时间】:2020-12-07 16:30:05
【问题描述】:
我从 txt 文件中获取输入并将其存储在 2D 向量中。那部分工作正常。一旦我尝试访问 2D 矢量的各个元素,我的程序似乎就会出错。根据我的搜索,我以正确的方式索引向量,所以有人知道为什么这会导致我的代码崩溃吗?
编辑:我正在正确访问向量。 getInput2D() 实际上未能将 temp_vec 附加到 output_vector。那么在这种情况下动态创建二维向量的正确语法是什么?
#include <iostream>
#include <string>
#include <fstream>
#include <stdio.h>
#include <vector.>
#include <cmath>
using namespace std;
vector<vector<string>> output_vector{};
void getInput2D() {
ifstream file("C:\\Users\\ImTheUser\\Documents\\input.txt");
string line;
vector<string> temp_vec;
if (file.is_open()) {
while (getline(file, line)) {
if (line[0] != ' ') {
temp_vec.push_back(line);
temp_vec.clear();
}
else {
output_vector.push_back(temp_vec);
temp_vec.clear();
}
}
}
file.close();
}
int main() {
getInput2D();
cout << output_vector[0][0] << endl;
return 0;
}
【问题讨论】:
-
您应该检查
output_vector的大小,然后在访问[1][2]之前检查其第二个子向量的大小。根据文件内容,向量的元素可能比您想象的要少 -
顺便说一句,你永远不会清除
temp_vec所以最后output_vector将包含相同的lines 多次 -
当我访问任何索引时程序崩溃,更新代码以访问 [0][0] 结果相同
-
没有以空格开头的行吗?如果是这样,您将永远不会将
temp_vec添加到output_vector。话虽如此,@largest_prime_is_463035818 已经确定了代码中的 2 个潜在问题,您可能应该修复并重新测试。 -
在
output_vector.push_back(temp_vec);之后你应该做temp_vec.clear();,在file.close();之前或之后你应该做output_vector.push_back(temp_vec);。在那个主题上,您根本不需要file.close();。 ifstream 的析构函数将为您关闭文件。