将对象向量保存到文件C ++ [英] Save vector of Objects to file C++

查看:65
本文介绍了将对象向量保存到文件C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,它代表我正在编程的游戏中地面的各个小块.我也有一个向量保存对象的实例.将此列表保存到文件的最佳方法是什么?我可以遍历向量并保存每个x,y坐标以及对象使用的图像,但这似乎有些粗糙.我可以使用boost头文件,但是当我尝试构建和使用其余的boost时,目前存在一些主要问题.有什么建议吗?

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?

推荐答案

C ++没有内置的序列化功能,因此,如果要保存的对象几乎不需要或现在不需要构建,那么您所做的一切都会有点粗暴".(例如int,float等),然后您就可以一次性写出整个矢量,就像这样:

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));

但是,如果您有需要多步构造函数的数据类型(例如std :: string),那么您必须循环遍历每个元素,并用足够的信息分别写出它们以从磁盘读取数据时重建对象.

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.

这篇关于将对象向量保存到文件C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆