在 C++ 中迭代二维向量时出现超出范围的错误

Getting an out of range error iterating through a 2d vector in C++

已编辑
出于某种原因,当我 运行 在 Repl.it 上执行此操作时,我收到 out_of_range 错误

我想做的就是垂直 遍历一个二维向量,并做一些其他的实现。 这是代码:

#include <iostream>
#include <vector>
using namespace std;

void matrixElementsSum(vector<vector<int>> matrix) {
    int sum = 0;
    int i = 0;
    for (int j = 0; j < matrix.at(j).size(); j++)
    {
      
      for(i = 0; i<matrix.size(); i++)
      {
        cout << matrix.at(i).at(j) << " ";
        
      }
      
      cout << endl;
      
    }
}


int main() 
{
  vector<vector<int>> vect
    {
        {1, 1, 1, 0},
        {0, 5, 0, 1},
        {2, 1, 3, 10}
    };

   cout << matrixElementsSum(vect);

  return 0;
}

输出为

1 0 2 
1 5 1 
1 0 3 

terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check: __n (which is 3) >= this->size() (which is 3)


通常情况下,这个错误意味着我正在尝试读取矢量大小,但这里不是这种情况(至少,我是这么认为的)
很难理解这里出了什么问题。我将不胜感激任何帮助



注意:不想水平迭代

必须交换2个循环中的条件:

void matrixElementsSum(vector<vector<int>> matrix) {
    int sum = 0;
    int i = 0;
    int nRow = matrix.size();
    int nCol = matrix[0].size();
    for (int j = 0; j < nCol; j++)
    {
        for (i = 0; i < nRow; i++)
        {
            cout << matrix[i][j] << " ";
        }

        cout << endl;
    }
}

代码已更新为更易于解释。要查找列数,您无需检查每行中的元素数(大小);只有第一行就足够了。当列数多于行数时,代码会中断,并且在您超出之后 matrix[j] 不存在,因为它不是方矩阵,这就是 matrix[j].size(); 失败的原因。

作为 in the comments by Daniel Langr:

for (int j = 0; j < matrix.at(j).size(); j++) - How do you know that matrix has an element with index j?

最好将外循环限制为最长行的(先前计算的)大小,并在尝试访问之前检查内循环中的特定元素是否存在。

#include <algorithm>
#include <iomanip>      // std::setw
#include <iostream>
#include <vector>

void matrixElementsSum(std::vector<std::vector<int>> const& matrix, int width)
{ //                                                 ^^^^^^   
    
    auto const longest_row{
        std::max_element( matrix.cbegin(), matrix.cend()
                        , [](auto const& a, auto const& b) {
                              return a.size() < b.size();
    } )};

    auto const max_columns{ longest_row != matrix.cend() ? longest_row->size() : 0 };
    
    for ( size_t col{}; col < max_columns; ++col )
    {
        for( auto const& row : matrix )
        {
            if ( col < row.size() )
                std::cout << std::setw(width) << row[col];
            else
                std::cout << std::setw(width) << "";   
        }
        std::cout << '\n';
    }
}

int main() 
{
    std::vector<std::vector<int>> vect{
        {1, 1, 1, 0},
        {0, 5, 0, 1},
        {2, 1, 3, 10}
    };

//    std::cout << matrixElementsSum(vect);
//                 ^ It's a function returning void, how could this compile?

    matrixElementsSum(vect, 3);

    return 0;
}

如果每个向量的长度相同,那么只要保存大小就足够了,假设至少有一个元素。

void blabla(vector<vector<int>> matrix) {
    if (matrix.size() == 0) return;
    const size_t jmax = matrix.front().size();
    for (size_t j = 0; j < jmax; j++)
      for(size_t i = 0; i < matrix.size(); i++)
           cout << matrix.at(i).at(j) << " ";
}