How can I serialize an std::vector with boost::serialization?
class workflow {
private:
friend class boost::serialization::access;
开发者_StackOverflow
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?
#include <boost/serialization/vector.hpp>
Also read tutorial.
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
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];
}
}
}
sorry, I solved using
ar & BOOST_SERIALIZATION_NVP(tasks);
tnx bye
精彩评论