Serialise and deserialise vector in binary

前端 未结 4 1213
时光说笑
时光说笑 2020-12-11 21:42

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 us

4条回答
  •  [愿得一人]
    2020-12-11 21:53

    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  v;
    };
    

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

提交回复
热议问题