C++ 如何使用 boost::serialization 序列化 std::vector?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4276203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I serialize an std::vector with boost::serialization?
提问by Giuseppe
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?
如何使用 boost 库序列化成员“任务”?
回答by Marcin
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:
由于我使用 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
回答by Pijar
In case someone will ever need to write explicit 'serialize' method withoutany includes of boost headers (for abstract purposes, etc):
如果有人需要编写显式的“序列化”方法而不包含任何 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];
}
}
}
回答by Giuseppe
sorry, I solved using
抱歉,我解决了使用
ar & BOOST_SERIALIZATION_NVP(tasks);
tnx bye
再见