Highlighting elements in C ++ vector after declaration

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.
+3
source share
4 answers

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

v1.resize(20);
+5
source

If you want to read as many values ​​from cinas available, you can use a range of iterators istream_iteratorand pass this to the range constructor vector, for example:

#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>() );

(extra brackets are needed to prevent "C ++ most vexing parse" ). Wed also Building a vector using istream_iterators .

+3
source

resize :

v1.resize(20);
+2

vector :: resize () will resize it and fill it with default objects (int, in this case, it does not matter).

vector :: reserve () will allocate space without filling it.

You can add additional elements using, for example, push_back (), until you have as many items that you need - if necessary, it will resize.

+2
source

All Articles