fill a simple dynamic array in c++ with vector

3057 views c++
1

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

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

5

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.

posted this
10

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

posted this

Have an answer?

JD

Please login first before posting an answer.