如果我确定我的输入流包含 10 个值,我可以用
std::copy_n(std::istream_iterator<T>(input), 10, output);
Run Code Online (Sandbox Code Playgroud)
如果我不知道我有多少值,我可以用
std::copy(std::istream_iterator<T>(input), std::istream_iterator<T>(), output);
Run Code Online (Sandbox Code Playgroud)
我的问题是如何读取最多10 个值。我试图在这里对 I/O 错误保持稳健,但它似乎copy_n会尝试读取输入的末尾(它不知道它应该停止),并且copy不会在 10 个值处停止。我必须自己滚动copy_at_most吗?
(好吧,无论如何,显然对 copy_n 有一些困惑:std::istream_iterator<> 与 copy_n() 和朋友)
你可以使用copy_if一个计数器 - 不幸的是它不会提前损坏。
int count = 0;
std::copy_if(std::istream_iterator<T>(input), std::istream_iterator<T>(), output,
[&]() { return ++count < 10; });
Run Code Online (Sandbox Code Playgroud)
如果您想坚持使用算法(而不是简单的for循环),我建议您自己动手(我过去回答过类似的问题。)
| 归档时间: |
|
| 查看次数: |
612 次 |
| 最近记录: |