Using std :: istream_iterator to read up to N values

If I know for sure that my input stream contains 10 values, I can read them using

std::copy_n(std::istream_iterator<T>(input), 10, output); 

If I don’t know how many values ​​I have, I can read them all with

 std::copy(std::istream_iterator<T>(input), std::istream_iterator<T>(), output); 

My problem is how to read up to 10 values. I try to be sure of I / O errors here, but it seems that copy_n will try to read beyond the end of the input (it does not know that it should stop), and copy will not stop at 10 values. Should I roll my own copy_at_most ?

(Well, apparently, some kind of confusion in copy_n: std :: istream_iterator <gt with copy_n () and friends )

+4
source share
2 answers

Unfortunately, there is currently no way to limit the number of items processed using STL algorithms. My personal opinion is that std::copy() should take two ranges, both limited to start and end. If none of the ends can be reached, the corresponding range will be unlimited. That is, if anything, I would throw my own copy() algorithm as follows:

 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 cope with the current iterator system, comparison between output iterators is actually not possible. Thus, comparison for the output iterator actually requires a bit of programming of the templates to ensure that the actual output iterators are never compared, and true returned instead. For all other classes of iterators, the above algorithm should work (provided that I did not introduce any typos).

+3
source

You can use copy_if and a counter, which, unfortunately, is not interrupted before.

 int count = 0; std::copy_if(std::istream_iterator<T>(input), std::istream_iterator<T>(), output, [&]() { return ++count < 10; }); 

If you want to stick with algorithms (instead of just a for loop), I would advise you to use you (I answered a similar question ) in the past.)

+1
source

Source: https://habr.com/ru/post/1502413/


All Articles