Using std::istream_iterator to read up to N values

后端 未结 2 1171
-上瘾入骨i
-上瘾入骨i 2021-01-19 05:00

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);
         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-19 05:40

    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 
    std::pair
    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).

提交回复
热议问题