JASON
JASON

Reputation: 7491

Dynamic allocation of nested vectors

I did something like:

Grid(int row, int col):num_of_row_(row), num_of_col_(col) {
     grid_ = new vector<vector<bool> > (row, col);  
}

which dynamically allocates nested vector. Is this correct? I mean using this syntax:

new vector<vector<type> > (outersize, innersize)

where ** outersize, innersize are both "int" variables.**

update: I actually used this code, and it works. I just want to find out why.

Upvotes: 1

Views: 453

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727087

The second parameter passed to the constructor is the element of the vector to be repeated outersize times. You should use this syntax:

new vector<vector<type> > (outersize, vector<type>(innersize, elementValue));

For example, to make a 50x25 grid of bool initially set to true, use:

vector<vector<bool> > *grid = new vector<vector<bool> >(50, vector<bool>(25, true));

Upvotes: 2

Related Questions