Reputation: 2823
Here is my code:
std::vector< std::vector<int> > v;
v.push_back(std::vector<int>(2));
v[0].push_back(10);
std::cout<<(v[0])[0];
But it prints "0" instead of 10.
I am trying to make a dynamic vector that holds a vector with fixed size.
Can someone help me visualize what's happening?
Upvotes: 0
Views: 109
Reputation: 2823
After reading more about push_back, here's what i understand so far and how i fixed it
std::vector< std::vector<int> > vo; //empty vector of vectors
v.push_back(std::vector<int>(2)); //insert element
v.push_back(std::vector<int>(2)); //insert element
v[0][0] = 1;
v[0][1] = 2; //allocated so it's alright to add elements
v[1][0] = 3;
v[1][1] = 4;
std::cout<<v[1][1]; //4
Upvotes: 0
Reputation: 7129
The code is buggy:
std::vector<int>(2)
makes a vector of size 2 initialized with deault constructed int
(which is zero), so pushing 10
just makes a vector of size 3 w/ 10
at the end (index 2).
Upvotes: 3