How can I serialize an std::vector with boost::serialization?

25,749

Solution 1

#include <boost/serialization/vector.hpp>

Also read tutorial.

Solution 2

Just to add a generic example to this question. Lets assume we want to serialize a vector without any classes or anything. This is how you can do it:

#include <iostream>
#include <fstream>

// include input and output archivers
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

// include this header to serialize vectors
#include <boost/serialization/vector.hpp>

using namespace std;



int main()
{

  std::vector<double> v = {1,2,3.4, 5.6};

  // serialize vector
  {
    std::ofstream ofs("/tmp/copy.ser");
    boost::archive::text_oarchive oa(ofs);
    oa & v;
  }

   std::vector<double> v2;

   // load serialized vector into vector 2
   {
     std::ifstream ifs("/tmp/copy.ser");
     boost::archive::text_iarchive ia(ifs);
     ia & v2;
   }

   // printout v2 values
   for (auto &d: v2 ) {
      std::cout << d << endl;
   }


  return 0;
}

Since I use Qt, this is my qmake pro file contents, showing how to link and include boost files:

TEMPLATE = app
CONFIG -= console
CONFIG += c++14
CONFIG -= app_bundle
CONFIG -= qt

SOURCES += main.cpp


include(deployment.pri)
qtcAddDeployment()

INCLUDEPATH += /home/m/Downloads/boost_1_57_0


unix:!macx: LIBS += -L/home/m/Downloads/boost_1_57_0/stage/lib -lboost_system
unix:!macx: LIBS += -L/home/m/Downloads/boost_1_57_0/stage/lib -lboost_serialization

Solution 3

In case someone will ever need to write explicit 'serialize' method without any includes of boost headers (for abstract purposes, etc):

std::vector<Data> dataVec;
int size; //you have explicitly add vector size

template <class Archive>
void serialize(Archive &ar, const unsigned int version)
{
    if(Archive::is_loading::value) {
        ar & size;
        for(int i = 0; i < size; i++) {
            Data dat;
            ar & dat;
            dataVec.push_back(dat);
        }
    } else {
        size = dataVec.size();
        ar & size;
        for(int i = 0; i < size; i++) {
            ar & dataVec[i];
        }
    }
}

Solution 4

sorry, I solved using

ar & BOOST_SERIALIZATION_NVP(tasks);

tnx bye

Share:
25,749
Giuseppe
Author by

Giuseppe

Updated on May 30, 2020

Comments

  • Giuseppe
    Giuseppe almost 4 years
    class workflow {
    
    private:
    friend class boost::serialization::access;
    
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
      ar & tasks;
      ar & ID;
    }
    
     vector<taskDescriptor> tasks;
     int ID;
    

    How can i serialize the member "tasks" using boost libraries?

  • Ogre Psalm33
    Ogre Psalm33 almost 8 years
    The text "vector" does not occur in the linked documentation.
  • Fahim Hassan
    Fahim Hassan over 3 years
    could you tell me how it works? i have been trying to find out too