以二进制序列化和反序列化向量 [英] Serialize and deserialize vector in binary

查看:37
本文介绍了以二进制序列化和反序列化向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试将向量 (std::vector) 序列化为二进制格式,然后正确反序列化并能够读取数据时遇到问题.这是我第一次使用二进制格式(我使用的是 ASCII,但现在已经变得太难使用了)所以我从一个简单的整数向量开始.

I am having problems trying to serialise a vector (std::vector) into a binary format and then correctly deserialise it and be able to read the data. This is my first time using a binary format (I was using ASCII but that has become too hard to use now) so I am starting simple with just a vector of ints.

每当我读回数据时,向量总是具有正确的长度,但数据要么是 0,要么是未定义的,要么是随机的.

Whenever I read the data back the vector always has the right length but the data is either 0, undefined or random.

class Example  
{  
public:  
    std::vector<int> val;  
};

写:

Example example = Example();  
example.val.push_back(10);  
size_t size = sizeof BinaryExample + (sizeof(int) * example.val.size()); 

std::fstream file ("Levels/example.sld", std::ios::out | std::ios::binary);

if (file.is_open())  
{  
    file.seekg(0);  
    file.write((char*)&example, size);  
    file.close();  
}

阅读:

BinaryExample example = BinaryExample();

std::ifstream::pos_type size;  
std::ifstream file ("Levels/example.sld", std::ios::in | std::ios::binary | std::ios::ate);

if (file.is_open())  
{   
    size = file.tellg();

    file.seekg(0, std::ios::beg);
    file.read((char*)&example, size);
    file.close();
}

有谁知道我做错了什么或该做什么或能够指出我需要做的方向吗?

Does anyone know what I am doing wrong or what to do or be able to point me in the direction that I need to do?

推荐答案

您不能通过覆盖现有实例来反序列化非 POD 类,就像您似乎正在尝试做的那样 - 您需要为该类提供一个构造函数从流中读取数据并用它构造类的新实例.

You can't unserialise a non-POD class by overwriting an existing instance as you seem to be trying to do - you need to give the class a constructor that reads the data from the stream and constructs a new instance of the class with it.

大体上,给出如下内容:

In outline, given something like this:

class A {
    A();   
    A( istream & is );    
    void serialise( ostream & os );
    vector <int> v;
};

然后 serialise() 将写入向量的长度,然后是向量内容.构造函数将读取向量长度,使用长度调整向量大小,然后读取向量内容:

then serialise() would write the length of the vector followed by the vector contents. The constructor would read the vector length, resize the vector using the length, then read the vector contents:

void A :: serialise( ostream & os ) {
    size_t vsize = v.size();    
    os.write((char*)&vsize, sizeof(vsize));
    os.write((char*)&v[0], vsize * sizeof(int) );
}

A :: A( istream & is ) {
    size_t vsize;
    is.read((char*)&vsize, sizeof(vsize));
    v.resize( vsize );
    is.read((char*)&v[0], vsize * sizeof(int));
}

这篇关于以二进制序列化和反序列化向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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