简体   繁体   中英

Accessing a dynamic vector of vector

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?

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM