Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 831
Giuseppe Avatar asked Nov 25 '10 10:11

Giuseppe


3 Answers

#include <boost/serialization/vector.hpp>

Also read tutorial.

like image 175
Abyx Avatar answered Oct 20 '22 17:10

Abyx


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
like image 24
Marcin Avatar answered Oct 20 '22 17:10

Marcin


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];
        }
    }
}
like image 4
Pijar Avatar answered Oct 20 '22 15:10

Pijar