istreambuf_iterator with structs
istreambuf_iterator with structs
我很难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 迭代器会很好,如果标准迭代器经过深思熟虑,它们似乎可以轻松涵盖所有这些用例。我想最短和最简单的解决方案是继续使用我的自定义迭代器。
ifstream
是 basic_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&)
....
- Problems with std::cin.fail()
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 这对"With a stackless coroutine, only the top-level routine may be suspended."意味着什么
- Boost.TEST with CLion: "Test framework quit unexpectedly"
- 避免碎片化的ClientHellos with OpenSSL (DTLS)
- Issues with Win32 ReadProcessMemory API
- Qt with WinAPI MouseProc
- [[maybe_unused]] with structured_binding?
- Issue with WriteProcessMemory
- OpenCV RTP-Stream with FFMPEG
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- std::adjacent_difference with std::chrono time_point
- DLL Made with CMake 使程序崩溃
- QtCreator with C 库中的链接器问题
- SHBrowseForFolder with BIF_BROWSEFORCOMPUTER and SHGetPathFr
- specialized std::default_delete with QQmlComponent
- VS2019 - Sudo Remote Debugging on Linux with Cmake project
- Inference pytorch C++ with alexnet and cv::imread image
- Pybind11: init<> with lambda
- istreambuf_iterator with structs