简体   繁体   English

访问向量的动态向量

[英]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. 但是它显示的是“ 0”而不是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). 会产生一个大小为2的向量,并使用deault构造的int (为零)初始化,因此推入10只会使大小为3 w / 10的向量在结尾处(索引2)。

After reading more about push_back, here's what i understand so far and how i fixed it 阅读更多有关push_back的信息之后,这是到目前为止我所了解的以及如何解决它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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