【问题标题】:Using std::istream_iterator to read up to N values使用 std::istream_iterator 读取最多 N 个值
【发布时间】:2013-09-16 13:03:36
【问题描述】:

如果我确定我的输入流包含 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<> with copy_n() and friends

【问题讨论】:

    标签: c++


    【解决方案1】:

    遗憾的是,目前一般没有办法限制使用 STL 算法处理的元素的数量。我个人的观点是std::copy() 应该采用两个范围,分别由开始和结束分隔。如果任一端都无法到达,则相应的范围将是无限的。也就是说,如果有什么我会像这样推出我自己的copy() 算法:

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

    要处理当前的迭代器系统,输出迭代器之间的比较实际上是做不到的。因此,输出迭代器的比较实际上需要一些模板编程来确保永远不会比较实际的输出迭代器,而是返回true。对于所有其他迭代器类,上述算法应该可以正常工作(假设我没有引入任何拼写错误)。

    【讨论】:

      【解决方案2】:

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

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

      如果你想坚持使用算法(而不是简单的 for 循环),我建议你自己动手(我过去回答过 similar question。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-26
        • 1970-01-01
        相关资源
        最近更新 更多