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

后端 未结 4 1109
星月不相逢
星月不相逢 2021-02-18 21:02
class workflow {

private:
friend class boost::serialization::access;

template
void serialize(Archive & ar, const unsigned int version)
{
  ar          


        
相关标签:
4条回答
  • 2021-02-18 21:26

    sorry, I solved using

    ar & BOOST_SERIALIZATION_NVP(tasks);
    

    tnx bye

    0 讨论(0)
  • 2021-02-18 21:37

    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
    
    0 讨论(0)
  • 2021-02-18 21:39

    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];
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-18 21:47
    #include <boost/serialization/vector.hpp>
    

    Also read tutorial.

    0 讨论(0)
提交回复
热议问题