istreambuf_iterator with structs

istreambuf_iterator with structs

本文关键字:structs with iterator istreambuf      更新时间:2023-10-16

我很难istreambuf_iterator使用char以外的其他类型。我们都知道您可以将流转换为这样的范围:

istreambuf_iterator<char>(ifstream("some_file")) //now we have an iterator that reads chars each step.

我有一个二进制结构流,而不是字符。所以我需要能够做到这一点:

istreambuf_iterator<MyStruct>(ifstream("some_file"))

我想轻松迭代流中的所有 MyStruct。我无法开始工作,因为ifstream是一个istream,它是一个只处理istreambuf_iterator<char>而不是istreambuf_iterator<MyStruct> basic_istream<char>

我已经编写了自己的迭代器,但我想使用 STD 迭代器,因为它看起来很完美。他们为什么要做这样的事情?为什么我不能使用 istreambuf_iterator 迭代 ifstream 中的结构?

编辑:

人们建议将istream_iterator与运算符>>的自定义实现一起使用。这将起作用,但对于我的特定用途,我需要读取特定数量的 MyStruct,直到 EOF。流包含,比如说 5,MyStruct 的数据,然后是更多不应该作为 MyStructs 读取的数据。所以我需要通过像这样偏移"开始迭代器"来为范围创建"结束迭代器":

auto begin = istream_iterator<MyStruct>(the_istream);
auto end = istream_iterator<MyStruct>(the_istream) + 5;

但我不知道这是否可能。

拥有一个具有所有这些功能的完全标准的 STL 迭代器会很好,如果标准迭代器经过深思熟虑,它们似乎可以轻松涵盖所有这些用例。我想最短和最简单的解决方案是继续使用我的自定义迭代器。

ifstreambasic_ifstream<char> 的 typedef。 由于您使用的是类型化为包含 char s 的流,因此您只能迭代 char s 也就不足为奇了。 你可能会想试试这个(我做到了(:

istreambuf_iterator<MyStruct>(basic_ifstream<MyStruct>("some_file"))

但它不起作用,因为它需要一个char_traits类来MyStruct,而char_traits反过来需要定义一个int_type在这种情况下,它将是一个包含MyStruct的整数。 据推测MyStruct不能以任何整数类型存储,所以我们不走运。

我想你已经知道你可以超载operator>>(istream&, MyStruct&)....