简体   繁体   中英

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:

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

你可以像这样使用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::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.

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