6

如果我确定我的输入流包含 10 个值,我可以使用

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

如果我不知道我有多少价值,我可以用

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

我的问题是如何读取多达10 个值。我试图在这里对 I/O 错误保持稳健,但似乎copy_n会尝试读取超过输入的结尾(它不知道应该停止),并且copy不会在 10 个值处停止。我必须自己动手copy_at_most吗?

(好吧,显然对 copy_n 有一些混淆:std::istream_iterator<> 与 copy_n() 和朋友

4

2 回答 2

4

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

于 2013-09-16T13:20:45.393 回答
2

您可以使用copy_ifand 一个计数器 - 不幸的是它不会提前中断。

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

如果你想坚持使用算法(而不是简单的for循环),我建议你自己动手(我过去回答了一个类似的问题。)

于 2013-09-16T13:17:21.137 回答