writing integer input to vector container in C++

18,543

Solution 1

To insert integer to a vector from console and print everything out:

int input;
vector<int> v;
while(cin >> input){
 v.push_back(input);
}

for(int i = 0; i<v.size(); i++){
 cout<< v[i] <<endl;
}

And vector also provides you to print out the max size with:

cout << v.max_size()<<endl;

Solution 2

If the vector isn't initialized with an initial capacity, then use something like this:

int temp;
for (...) {
    cin >> temp;
    v.push_back(temp);
}

Solution 3

Slightly more compact versions:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

std::istream_iterator< int > iterBegin( std::cin ), iterEnd;

// using the range constructor
std::vector< int > vctUserInput1( iterBegin, iterEnd );

// using the copy & back_inserter
std::vector< int > vctUserInput2;
std::copy( iterBegin, iterEnd, std::back_inserter( vctUserInput2 ) );

Solution 4

Try this

std::copy( std::istream_iterator<int>(std::cin),
            std::istream_iterator<int>(),
            std::back_inserter( v ) );

See here

You can simplify this to just creating the vector and initializing it with iterators:

std::vector<int>  v(std::istream_iterator<int>{std::cin},
                    std::istream_iterator<int>{});
Share:
18,543
maverick
Author by

maverick

Updated on June 04, 2022

Comments

  • maverick
    maverick almost 2 years

    likewise we do in array

    for (.....)
      cin>>a[i];
    

    how we can do this using vectors. i declared a vector of integers

    vector<int> v;
    

    now i need to take inputs from console and add append those in vector.i am using vector because i donot know the limit.