c++ - 数组填充错误

标签 c++ arrays

我不明白我的程序出了什么问题。我有这样的输入数据:

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功能有widthheight与您稍后在 showMatrix 中调用它的顺序不同。我建议交换 fillMatrix 中的顺序保持与showMatrix中的相同.

小心地将每一行填充到 tempLine.length ,可能大于width这将导致异常。您还可以从 showMatrix 内的 vector 获取宽度和高度。而不是将这些作为参数。正如@Charles 所说,您确实应该通过引用传递 vector 以避免进行复制。 fillMatrix 中的 vector 参数目前非常无用,因为您必须返回它,除非您将其转换为引用并使函数 void .

关于c++ - 数组填充错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4729759/

相关文章:

c++ - Visual C++如何正确调用 `dir`命令?

c# - 如何使用给定类型生成数组类型?

arrays - 如何在 SCSS 中获取数组的 $values?

java - 使用 Jackson 反序列化包含不同类型的 JSON 数组

javascript - 数组修改

android - 如何将数据库值获取到android(sqlite数据库)中的字符串数组

c++ - 在值 C++ 中搜索设置/取消设置位组合

c++ - 使用 ifstream::operator>> 从 CSV 文件加载数组

c++ 在另一个 std::string 中出现一个 std::string

c++ - operator<< with boost::variant 是如何实现的