If I want to read all integers from standard input to a vector, I can use the handy:
vector<int> v{istream_iterator<int>(cin), istream_iterator()};
But let's assume I only want to read n
integers. Is the hand-typed loop everything I got?
vector<int> v(n);
for(vector<int>::size_type i = 0; i < n; i++)
cin >> v[i];
Or is there any more right-handed way to do this?
As given in comments,
copy_n
is unsafe for this job, but you can usecopy_if
with mutable lambda:as pointed out in this answer: std::copy n elements or to the end
You usually shouldn't do this with
std::copy_n
, which assumes that the provided iterator, when incremented n times, remains valid:If you can guarantee that, then fine, but generally with
std::cin
that's not possible. You can quite easily have it dereferencing an invalid iterator:You're pretty much there with your loop, though I'd probably use stronger termination condition to avoid excess reads from a "dead" stream:
I'd be tempted actually to wrap this into something that's like
std::copy_n
, but accepts a full "range" whose bounds may be validated in addition to counting from 0 to N.An implementation might look like:
You'd use it like this:
Now you get M elements, where M is either the number of inputs provided or N, whichever is smaller.
(live demo)