I'm having a hard time getting istreambuf_iterator working with other types than char. We all know you can transform a stream into a range like this:
istreambuf_iterator<char>(ifstream("some_file")) //now we have an iterator that reads chars each step.
I have a binary stream of structs, not chars. So I need to be able to do this:
istreambuf_iterator<MyStruct>(ifstream("some_file"))
I want to easily iterate over all the MyStruct's in the stream. This I cannot get to work since ifstream is an istream which is an basic_istream<char>
which is only working with istreambuf_iterator<char>
, not istreambuf_iterator<MyStruct>
.
I have already written my own iterator but I wanted to use the STD iterator because it seemed perfect. Why did they make things like this? Why can I not iterate over structs in an ifstream using istreambuf_iterator?
Edit:
People have suggested using istream_iterator with a custom implementation of operator>>. This will work but for my specific use I need to read a specific amount of MyStruct's, not until EOF. The stream contains, say 5, MyStruct's and then more data that is not supposed to be read as MyStructs. So I need to create the "end-iterator" for the range by offsetting the "begin-iterator" like this:
auto begin = istream_iterator<MyStruct>(the_istream);
auto end = istream_iterator<MyStruct>(the_istream) + 5;
But this I don't know if it's possible.
It would be nice to have a fully standard STL iterator which has all these features and it seems they could easily have covered all these use cases if the standard iterators were somewhat more thought through. I guess the shortest and easiest solution is to keep using my custom iterator.
ifstream
is a typedef for basic_ifstream<char>
. Since you are using a stream which is typed as if it contains char
s, it's not surprising that you can only iterate over char
s. You might think to try this (I did):
istreambuf_iterator<MyStruct>(basic_ifstream<MyStruct>("some_file"))
But it won't work, because it requires a char_traits
class for MyStruct
, and char_traits
in turn requires defining an int_type
which in this case would be an integer that holds a MyStruct
. Presumably MyStruct
can't be stored in any integer type, so we're out of luck.
I assume you already know you can overload operator>>(istream&, MyStruct&)
....
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.