开发者

Allocating elements in C++ vector after declaration

开发者 https://www.devze.com 2023-03-03 09:38 出处:网络
Please refer to the code and comments below: vector<int> v1(10); cin>>v1[0]; // allowed cin>>v1[1]; // allowed

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 availabl开发者_StackOverflowe.


You simply need to resize the vector before adding the new values:

v1.resize(20);


You could use resize like this:

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:

#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"). Cf. also Constructing a vector with istream_iterators.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消