0

i m trying to fill a dynamique 2D array
where i m wrong

#include<vector>
cin<<x;
vector<vector<int>> tab(x);
for (int i = 0; i < x; i++)
{ 
    for (int j = 0; j < x; j++)
    {
        cin>>tab[i][j];
    }  
}

and also i want to print it to the screen

new user
  • 11
  • 4
  • given it is actually `cin >> x;` (note the direction of the operator) you have a vector of `x` vectors. these vectors `tab[i]` are empty. To fill them use `push_back()`. – Swordfish Nov 03 '18 at 19:43

2 Answers2

1

To create a std::vector of std::vectors of a given size x, use

std::vector<std::vector<int>> foo(x, std::vector<int>(x));

To print it you can use loops:

for (std::size_t row{}; row < x; ++row) {
    for (std::size_t col{}; col < x; ++col)
        std::cout foo[row][col] << ' ';
    std::cout.put('\n');
}

A more efficient way of having a matrix is to use a std::vector<int> of the total size of rows and columns and calculate the index accordingly:

std::vector<int> foo(x * x);

// access column `c` at row `r` like
foo[r * x + c];

Print it:

for(std::size_t i{}; i < x; ++i, std::cout.put('\n'))
    std::copy(foo.begin() + i * x, foo.begin() + (i+1) * x, 
              std::ostream_iterator<int>(std::cout, " "));
Swordfish
  • 12,971
  • 3
  • 21
  • 43
0
vector<vector<int>> tab(x)

This is only creating a vector for tab, but not for the subvectors.

Use:

vector<vector<int>> tab(x, vector<int>(x));

To populate the subvectors as well.

Be advised that this is not the most efficient way to create matrices.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62