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

后端 未结 4 1117
星月不相逢
星月不相逢 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: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 
    #include 
    
    // include input and output archivers
    #include 
    #include 
    
    // include this header to serialize vectors
    #include 
    
    using namespace std;
    
    
    
    int main()
    {
    
      std::vector 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 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
    

提交回复
热议问题