问题
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.
回答1:
You simply need to resize the vector before adding the new values:
v1.resize(20);
回答2:
You could use resize like this:
v1.resize(20);
回答3:
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.
回答4:
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.
来源:https://stackoverflow.com/questions/5922797/allocating-elements-in-c-vector-after-declaration