writing integer input to vector container in C++

蹲街弑〆低调 提交于 2019-12-10 10:27:19

问题


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.


回答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;



回答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);
}



回答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 ) );



回答4:


Try this

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

See here




回答5:


The easiest solution is with an istream_iterator. You don't want std::copy, tough, because that's greedy. It will read everything. Instead, use this:

std::istream_iterator<int> iter(std::cin);
vector<int> v;
for(.....)
   v.push_back(*iter++);



回答6:


Small program for taking input from user through vector in c++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    vector<int> v1;
    int input;
    cout<<"Enter elements in vector";
      for (int i=0;i<10;i++)
       {
         cin>>input;
         v1.push_back(input);
       }

       cout<<"Elements in vector";
       for (int i=0;i<10;i++)
        {
          cout<<v1[i]<<"\n";
        }
         return 0;
 }


来源:https://stackoverflow.com/questions/5001156/writing-integer-input-to-vector-container-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!