Consider the following code piece:
...
int N,var;
vector nums;
cin >> N;
while (N--)
{
cin >> var;
nums.push_back(var);
}
...
>
Assuming you have already read the initial N
, there is a nice trick using istream_iterator
:
std::vector nums;
nums.reserve(N);
std::copy(std::istream_iterator(std::cin),
std::istream_iterator(),
std::back_inserter(nums));
The back_inserter
object turns itself into an iterator that adds elements to the vector at the end. Iterator streams can be parameterized by the type of the elements read, and, if no parameter given, signals the end of input.