expiring_noob
expiring_noob

Reputation: 57

C++ Boost serialization of a matrix of vectors

I'm using <boost/serializaton>, and I need to serialize a matrix of vectors, member of a class X1, say:

vector<vector<vector<vector<X2>>>> V;

where:

The question is: how can I serialize V?

I tried different approaches but no one worked. I have read the documentation in the Boost site and its examples, but I’m missing something though. Here it is the thing:

    #include <boost/archive/binary_iarchive.hpp>
    #include <boost/archive/binary_oarchive.hpp>
    #include <boost/serialization/vector.hpp>

    // I tried with the simplest way:
    class X1{
    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive& ar, const unsigned int version) {
        ar & V;
        }
    //…
    }; 

    // or by calling serialization in a explicit way for each object of V:            
    class X1{ 
    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive& ar, const unsigned int version) {
        ar & V;
            for (auto it = V.begin(); it != V.end(); ++it) {
            ar & *it;
                for (auto jt = (*it).begin(); jt != (*it).end(); ++jt) {
                ar & *jt;
                    for (auto kt = (*jt).begin(); kt != (*jt).end(); ++kt) {
                    ar & *kt;
                        for (auto wt = (*kt).begin(); wt != (*kt).end(); ++wt) {
                        ar & *wt;
                        }
                    }
                }
            }
        }
    //…
    }; 

I tried the latter (maybe I should do it reversely?) also using ranges, and other different ways too that honestly I have deleted and don’t remember: it serializes but crashes when reading from the serialized file. I hope to have expressed myself clearly, it’s my first question. Thanks for the help!

Upvotes: 2

Views: 1257

Answers (1)

sehe
sehe

Reputation: 392954

Vector support is builtin, so

template<class Archive>
    void serialize(Archive& ar, const unsigned int version) {
        ar & V;
    }

is the right thing for the datastructure.

Upvotes: 4

Related Questions