Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22094

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.

Upvotes: 5

Views: 13377

Answers (4)

Marc Mutz - mmutz
Marc Mutz - mmutz

Reputation: 25293

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.

Upvotes: 3

jwismar
jwismar

Reputation: 12258

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.

Upvotes: 2

Bart
Bart

Reputation: 20028

You could use resize like this:

v1.resize(20);

Upvotes: 4

Aaron
Aaron

Reputation: 9193

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

v1.resize(20);

Upvotes: 9

Related Questions