Consider the following code piece:
...
int N,var;
vector<int> nums;
cin >> N;
while (N--)
{
cin >> var;
nums.push_back(var);
}
...
Is it possible to do this without using an auxillary variable, in this case var
?
Assuming you have already read the initial N
, there is a nice trick using istream_iterator
:
std::vector<int> nums;
nums.reserve(N);
std::copy(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
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.
If you don't have already copy_n()
in your toolbelt then you should. Very useful.
template<class In, class Size, class Out>
Out copy_n(In first, In last, Size n, Out result)
{
while( n-- > 0 && first != last )
*result++ = *first++;
return result;
}
With this utility it's convenient and elegant to copy n elements into a vector:
#include<iterator>
#include<vector>
#include<iostream>
// ...
int n = 0;
std::cin >> n;
std::vector<int> v(n);
copy_n(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(),
n,
v.begin());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With