c++vector2d-vector

getting an extra unwanted value when resizing 2d vector


I am trying to create a 4x3 matrix. There should be four 4 columns and 3 rows. it should look like this:

000
000
000
000

Instead I am getting this as an output when I print out my 2d vector:

0000
0000
0000
0000

This my simple code:

 #include <iostream>
 #include <vector>
    
int main(void) {
  
 
std::vector< std::vector<int> > matrix;

matrix.resize(4, std::vector<int>(3));

    for (unsigned int i = 0; i < matrix.size(); i++)
  {
    for (unsigned int j = 0; j < matrix.size(); j++)
    {
      std::cout << matrix[i][j];
    }
    std::cout << std::endl;
  }

   return 0;
}

Could anyone help me ? Thanks in advance.


Solution

  • You access elements out of bounds, inner loop should be something like:

    for (unsigned int i = 0; i < matrix.size(); i++)
    {
        for (unsigned int j = 0; j < matrix[i].size(); j++)
        {
            std::cout << matrix[i][j];
        }
        std::cout << std::endl;
    }
    

    or even better:

    for( const auto &m : matrix ) {
         for( auto i : m )
            std::cout << i;
         std::cout << std::endl;
    }
    

    Note: it is not necessary to create empty vector and then resize it, when you can initialize it with proper size:

    std::vector< std::vector<int> > matrix(4, std::vector<int>(3));