Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

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

EDITED
For some reason when I run this on Repl.it, I get an out_of_range error

All I am trying to do is iterate through a 2d vector vertically, and do some other implementations. This is the code:

#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;
}

And output is

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)


Normally, this error means I am trying to read past the vector size but it is not the case here(at least, that is what I think)
It is hard understanding what is wrong here. I would appreciate any kind of help



Note: I don't want to iterate horizontally

question from:https://stackoverflow.com/questions/65661552/getting-an-out-of-range-error-iterating-through-a-2d-vector-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If each vector has the same length, it's enough to just save the size, assuming there is at least one element.

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) << " ";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...