我正在尝试读取一个包含整数值的文件并将每个值放入一个二维 vector 中。无论出于何种原因,我得到的 vector 全是零,而不是我刚刚从文件中读出的值。为什么会这样,我该如何解决?
void populateVector(string file, vector<vector<int>>& v, int rows, int cols){
ifstream read(file);
int val;
if (!read.is_open()) {
throw runtime_error("Output file is not open.");
} else {
//Populate 2D vector with values from file
while (read >> val) {
cout << val << endl; //Prints each value being processed. Prints proper value.
for (int i = 0; i < rows; i++) {
vector<int> newCol;
v.push_back(newCol);
for (int j = 0; j < cols; j++) {
v.at(i).push_back(val);
}
}
}
}
}
当我打印 vector 时,它只填充了零,即使打印到标准输出的读取值是我所期望的(文件中的值)。
最佳答案
您的解决方案会将所有数字“cols”次插入每一行,也就是说您最终得到 row * (cols * n) 矩阵。正确看待你的循环。
我假设您打算只读取每个数字一次。然后将循环更改为如下所示(根据需要添加错误检查)
for (int i = 0; i < rows; i++)
{
std::vector<int> newRow;
for (int j = 0; j < cols; j++)
{
int val;
read >> val;
newRow.push_back(val);
}
v.push_back(newRow);
}
关于c++ - 将文件中的值读入 2D vector 会导致所有值为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46735031/