Using std::istream_iterator to read up to N values

后端 未结 2 1169
-上瘾入骨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:39

    You could use copy_if and a counter - that unfortunately doesn't break early.

    int count = 0;
    std::copy_if(std::istream_iterator(input), std::istream_iterator(), 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.)

提交回复
热议问题