If I know for certain that my input stream contains 10 values, I can read them with
std::copy_n(std::istream_iterator(input), 10, output);
You could use copy_if
and a counter - that unfortunately doesn't break early.
int count = 0;
std::copy_if(std::istream_iterator<T>(input), std::istream_iterator<T>(), output,
[&]() { return ++count < 10; });
If you'd like to stick with algorithms (instead of plain for
loop), I'd suggest you roll you own (I answered a similar question in the past.)
Sadly, there is currently in general no way to limit the number of processed elements using STL algorithms. My personal view is that std::copy()
should take two ranges both delimited by begin and end. If either end can't be reached the corresponding range would be unbounded. That is, if anything I would roll my own copy()
algorithm like this:
template <typename InIt, typename OutIt>
std::pair<InIt, OutIt>
copy(InIt init, InIt inend, OutIt outit, OutIt outend) {
for (; init != inend && outit != outend; ++init, ++outit) {
*outit = *init;
}
return std::make_pair(init, outit);
}
To deal with the current iterator system, the comparison between output iterators actually can't be done. Thus, the comparison for output iterator actually requires a bit of template programming to make sure actual output iterators are never compared and, instead, true
is returned. For all other iterator classes the above algorithm should just work (assuming I didn't introduce any typos).