In this post, we will see how to resolve Reading and Writing std::vector<struct> to a file
Question:
I need to write avector
to a file, and then read it back into a vector
.The
vector
contains hundreds, possibly thousands, of struct
s which each contain 2 different struct
s.I thought that the best way to do it would be to get the pointer with
MyVector.data()
and somehow write the data using that.Just in case here’s a diagram of the
vector
:I tried multiple methods, such as
ofstream.write()
and fwrite()
, but none of them worked.binary ‘=’: no operator found which takes a right-hand operand of type ‘Frame’ (or there is no acceptable conversion)
Best Answer:
std::ostreambuf_iterator
writes character data to the output stream whenever it is assigned a single character via its operator=
. Since you are specifying char
as the CharT
template parameter of std::ostreambuf_iterator
, its operator=
expects a char
value to be assigned to it (ie, when used to write data from a std::vector<char>
, std::string
, etc), but you are trying to write Frame
objects from a std::vector<Frame>
instead. IOW, since you are trying to write Frame
objects where char
values are expected, that is why you are getting the conversion error on operator=
.You have a similar issue with reading in using
std::istreambuf_iterator
, too. It is meant for reading in character data (via its operator*
), not structured data.For what you are attempting to do, you need to use
std::ostream_iterator
(and std::istream_iterator
) instead. You will simply have to define an overloaded operator<<
(and operator>>
) for Frame
to write/read its member data to/from a std::ostream
/std::istream
as needed.Try this:
If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com