
2dimensional vectors
Hello,
I want to insert some My_Struct* pointers into a 2dimensional array. In a 1dimensional array, I normally do this by simply using the push_back function of a vector. But in 2dimensions, this doesn't seem to work. Here is what I tried:
Code:
vector<vector<My_Struct*> > my_vector;
for (int i = 0; i < 5; i ++)
{
for (int j = 0; j < 20; j ++)
{
My_Struct* x = new My_Struct();
my_vector.push_back(x);
}
}
I want to create a 5 x 20 vector, with each element pointing to a My_Struct object. But when I try this approach, I get the error "vector subscript out of range" at the first push_back(x) call.
How can I do this?
Thanks :)

You have to push_back each inner vector if you want to use push_back. Do that before the inner loop starts.
Another solution is simply to construct the vectors right away since you know the size beforehand: Code:
vector<vector<My_Struct*> > my_vector(5, vector<My_Struct*>(20));
Then instead of push_back you can access each location with [i][j] notation. They default to null pointers until you initialize them.