Save vector of Objects to file C++

2019-07-11 21:45发布

问题:

I have an object that represents the individual tiles of the ground in a game I am programming. I also have a vector holding instances of the object. What is the best way to save this list to a file? I could loop through the vector and save each x,y coordinate and what image the object uses but that seems a little crude. I can use the boost header files but currently have some major problems when I try to build and use the rest of boost. Any suggestions?

回答1:

C++ has no inbuilt serialization functionality, so whatever you do will be a little 'crude', generally, if the objects you're saving require little or now construction (such as int, floats, etc) then you can simply write out the entire vector in one go, like so:

std::vector <int> data(16, 0);
std::ofstream output("binary.data");
output.write(static_cast<char *>(&(data[0])), data.size()*sizeof(int));

However, if you've got data types which require multi-step constructors (such as std::string), then you must loop through each element and write them out individually with enough info to reconstruct the objects when reading from the disk.



回答2:

That certainly seems like a good enough solution to me. a format something like: {x, y, image_filename} would also make debugging a little easier, as you could, by inspection, verify whether your saving code or loading code is causing issues (if there arise any issues). I don't imagine you could save much space by using a binary solution anyway, since you'd need the full image_filename most likely.

You could look at what Boost::Serialization offers.



回答3:

I fully endorse Boost::Serialization. You can actually choose whether you want text or binary format. I usually write to/read from text archives during development/debugging and then switch to the binary format for deployment. Note that the binary format is not portable between different architectures, so stick to the text format if archive portability is a concern for you.

If your objects change or you wish to serialize derived classes it is very easy to do so, and you can do archive versioning as well. There is really no need to re-implement this particular wheel :-)

Maybe you can provide more information on what problems you are experiencing with your Boost installation (version? OS? compiler?), surely someone will help.