使用std :: istream_iterator读取最多N个值 [英] Using std::istream_iterator to read up to N values

查看:76
本文介绍了使用std :: istream_iterator读取最多N个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I know for certain that my input stream contains 10 values, I can read them with

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

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

If I don't know how much values I have, I can read all of them with

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

我的问题是如何最多读取10个值.我正在尝试在这里针对I/O错误进行增强,但是看来 copy_n 会尝试读取输入结尾之后的内容(它不知道应该停止输入),并且 copy 不会在10个值处停止.我是否必须滚动自己的 copy_at_most ?

My problem is how to read up to 10 values. I'm trying to be robust against I/O errors here, but it appears that copy_n will try to read past the end of the input (it doesn't know that it should stop), and copy won't stop at 10 values. Do I have to roll my own copy_at_most?

(好吧,无论如何,copy_n显然还是有些混乱:推荐答案

遗憾的是,当前通常没有办法限制使用STL算法处理的元素的数量.我个人的观点是, std :: copy()应该采用两个范围,均以begin和end分隔.如果无法到达任何一端,则相应范围将是无界的.就是说,如果有什么话,我会像这样滚动我自己的 copy()算法:

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

要处理当前的迭代器系统,实际上无法完成输出迭代器之间的比较.因此,对输出迭代器的比较实际上需要进行一些模板编程,以确保从不对实际的输出迭代器进行比较,而是返回 true .对于所有其他迭代器类,上述算法应该可以正常工作(假设我没有引入任何错别字).

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

这篇关于使用std :: istream_iterator读取最多N个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆