简体   繁体   English

声明后在C ++向量中分配元素

[英]Allocating elements in C++ vector after declaration

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.

您只需在添加新值之前调整向量的大小:

v1.resize(20);

If you want to read as many values from cin as are available, you can use an istream_iterator iterator range and pass that to the vector range-constructor, like this: 如果要从可用的cin读取尽可能多的值,可以使用istream_iterator迭代器范围并将其传递给vector范围构造函数,如下所示:

#include <iterator> // for istream_iterator
#include <vector>
#include <iostream> // for cin

// ...

std::vector<int> v1( (std::istream_iterator<int>( std::cin )), // extra ()
                     std::istream_iterator<int>() );

(the extra parentheses are required to prevent "C++ most vexing parse" ). (需要额外的括号来防止“C ++最令人烦恼的解析” )。 Cf. 参看 also Constructing a vector with istream_iterators . 使用istream_iterators构造向量

你可以像这样使用resize

v1.resize(20);

vector::resize() will resize it and fill it with default constructed objects (int, in this case, so it doesn't matter). vector :: resize()将调整它的大小并用默认的构造对象填充它(int,在这种情况下,所以没关系)。

vector::reserve() will allocate space, without filling it. vector :: reserve()将分配空间,而不填充它。

You can add additional items using, for example, push_back(), until it has however many items you want - it resizes itself as needed. 您可以使用例如push_back()添加其他项目,直到它具有您想要的多个项目 - 它会根据需要调整自身大小。

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

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