I want to insert some My_Struct* pointers into a 2-dimensional array. In a 1-dimensional array, I normally do this by simply using the push_back function of a vector. But in 2-dimensions, this doesn't seem to work. Here is what I tried:
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.
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();
How can I do this?
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:
Then instead of push_back you can access each location with [i][j] notation. They default to null pointers until you initialize them.
vector<vector<My_Struct*> > my_vector(5, vector<My_Struct*>(20));