在 C++ 中分配元素声明后的向量
请参考下面的代码和注释:
vector<int> v1(10);
cin>>v1[0]; // allowed
cin>>v1[1]; // allowed
// now I want v1 to hold 20 elements so the following is possible:
cin>>v1[15]>>v[19]; // how to resize the v1 so index 10 to 19 is available.
Please refer to the code and comments below:
vector<int> v1(10);
cin>>v1[0]; // allowed
cin>>v1[1]; // allowed
// now I want v1 to hold 20 elements so the following is possible:
cin>>v1[15]>>v[19]; // how to resize the v1 so index 10 to 19 is available.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您只需在添加新值之前调整向量的大小:
You simply need to resize the vector before adding the new values:
您可以像这样使用 resize :
You could use resize like this:
如果您想从
cin
读取尽可能多的可用值,您可以使用istream_iterator
迭代器范围并将其传递给vector
范围 -构造函数,如下所示:(需要额外的括号来防止 "C++ 最令人烦恼的解析”)。比照。还使用 istream_iterators 构造向量。
If you want to read as many values from
cin
as are available, you can use anistream_iterator
iterator range and pass that to thevector
range-constructor, like this:(the extra parentheses are required to prevent "C++ most vexing parse"). Cf. also Constructing a vector with istream_iterators.
vector::resize() 将调整它的大小并用默认构造对象填充它(在本例中为 int,所以这并不重要)。
vector::reserve() 将分配空间,但不填充它。
您可以使用例如 Push_back() 添加其他项目,直到它具有您想要的数量 - 它会根据需要调整自身大小。
vector::resize() will resize it and fill it with default constructed objects (int, in this case, so it doesn't matter).
vector::reserve() will allocate space, without filling it.
You can add additional items using, for example, push_back(), until it has however many items you want - it resizes itself as needed.