我不明白我的程序出了什么问题。我有这样的输入数据:
01000
11110
01000
我想将其保存到:vector< vector<int> > matrix;
vector< vector<int> > fillMatrix(vector< vector<int> > matrix, int height, int width, ifstream &read)
{
// Make 2d-array [matrix]
matrix.resize(width);
for (int i=0; i < width; ++i)
matrix[i].resize(height);
// Fill it up with data
for (int i=0; i < height; ++i)
{
std::string tempLine;
std::getline(read, tempLine);
for (int j=0; j < tempLine.length(); ++j)
{
// This shows right information
//std::cout << tempLine[j] << " - " << (int)(tempLine[j] - '0') << "\n";
matrix[i][j] = (int)(tempLine[j] - '0');
}
}
return matrix;
}
matrix = fillMatrix(matrix, 3, 5, ifstreamHandle);
现在,显示矩阵的函数:
void showMatrix(vector< vector<int> > matrix, int width, int height)
{
// Show the matrix
for (int i=0; i < height; ++i)
{
for (int j=0; j < width; ++j)
{
std::cout << matrix[i][j];
}
std::cout << "\n";
}
}
showMatrix(matrix, 5, 3);
结果为showMatrix
是:
01000
11100
01000
第二行缺少“1”。怎么了?
最佳答案
当你初始化 vector 时,你的宽度和高度是错误的。当您稍后读取最后两列时,结果将是不确定的。
matrix.resize(width);
for (int i=0; i < width; ++i)
matrix[i].resize(height);
应该是
matrix.resize(height);
for (int i=0; i < height; ++i)
matrix[i].resize(width);
您的fillMatrix
功能有width
和height
与您稍后在 showMatrix
中调用它的顺序不同。我建议交换 fillMatrix
中的顺序保持与showMatrix
中的相同.
小心地将每一行填充到 tempLine.length
,可能大于width
这将导致异常。您还可以从 showMatrix
内的 vector 获取宽度和高度。而不是将这些作为参数。正如@Charles 所说,您确实应该通过引用传递 vector 以避免进行复制。 fillMatrix
中的 vector 参数目前非常无用,因为您必须返回它,除非您将其转换为引用并使函数 void
.
关于c++ - 数组填充错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4729759/