使用std :: istream

编程入门 行业动态 更新时间:2024-10-08 03:25:36
本文介绍了使用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显然还是有些混乱: std :: istream_iterator<>与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

本文发布于:2023-11-30 15:17:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650480.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:std   istream

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!