问题
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