连载和二进制deserialise矢量

连载和二进制deserialise矢量

本文介绍了连载和二进制deserialise矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有试图连载一个向量(的std ::矢量)转换成二进制格式的问题,然后正确地deserialise它和能够读取的数据。这是使用二进制格式我第一次(我是用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();
}

READ:

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?

推荐答案

您不能因为你似乎想要做unserialise通过改写现有的实例非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.

在大纲,给出这样的:

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

然后连载()将写矢量后跟向量内容的长度。构造函数会读取向量长度,采用长度调整向量,然后读取向量内容。未测试code:

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. Untested code:

void A :: serialise( ostream & os ) {
    size_t vsize = v.size();
    os.write((char*)&vsize, sizeof(vsize));
    os.write((vchar*)&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));
}

这篇关于连载和二进制deserialise矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:46