如何使用boost :: serialization序列化std :: vector?

时间:2010-11-25 10:52:23

标签: c++ boost vector 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;

如何使用boost库序列化成员“任务”?

4 个答案:

答案 0 :(得分:28)

#include <boost/serialization/vector.hpp>

另请阅读tutorial

答案 1 :(得分:11)

只是为这个问题添加一个通用示例。让我们假设我们想要序列化一个没有任何类或任何东西的向量。这就是你如何做到的:

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

由于我使用Qt,这是我的qmake pro文件内容,显示了如何链接和包含boost文件:

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

答案 2 :(得分:4)

如果有人需要编写显式的'序列化'方法而不用任何包含boost标头(用于抽象目的等):

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

答案 3 :(得分:1)

抱歉, 我用

解决了
ar & BOOST_SERIALIZATION_NVP(tasks);

TNX 再见