fill a simple dynamic array in c++ with vector

3057 views c++

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

vector<vector<int>> tab(x);
for (int i = 0; i < x; i++)
    for (int j = 0; j < x; j++)

and also i want to print it to the screen

answered question

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().

2 Answers


vector<vector<int>> tab(x)

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


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.

posted this

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] << ' ';

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];

posted this

Have an answer?


Please login first before posting an answer.