序列化、反序列化一个map对象:
#include <fstream> #include "boost/archive/binary_oarchive.hpp" #include "boost/archive/binary_iarchive.hpp" #include <boost/serialization/map.hpp> int main() { //序列化 std::map<int, std::string> mapOut; mapOut.insert({ 1, "mapItem1" }); mapOut.insert({ 2, "mapItem2" }); std::ofstream outFile("Seri.bin", std::ofstream::binary); boost::archive::binary_oarchive oa(outFile); oa << mapOut; outFile.close(); //反序列化 std::map<int, std::string> mapIn; std::ifstream inFile("Seri.bin", std::ofstream::binary); boost::archive::binary_iarchive ia(inFile); ia >> mapIn; getchar(); return 0; }
浸入式序列化:如果我们想要序列化一个非C++标准类的对象,那么可以采用浸入式序列化/反序列化方式:在类中添加序列化/反序列化方法serialize的实现,声明boost::serialization::access为友元,这样就可以直接使用<<、>>来序列化、反序列化该对象。
#include <fstream> #include "boost/archive/binary_oarchive.hpp" #include "boost/archive/binary_iarchive.hpp" #include <boost/serialization/map.hpp> class MyMap { public: void serialization(std::ofstream& ostream) //序列化 { boost::archive::binary_oarchive oa(ostream); oa << *this; } void unserialization(std::ifstream& istream) //反序列化 { boost::archive::binary_iarchive ia(istream); ia >> *this; } void insert(std::pair<int, std::string> pairData) { mapData.insert(pairData); size = mapData.size(); } private: friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & mapData; ar & size; } std::map<int, std::string> mapData; int size; }; int main() { //序列化 MyMap mapOut; mapOut.insert({ 1, "mapItem1" }); mapOut.insert({ 2, "mapItem2" }); std::ofstream outFile("Seri.bin", std::ofstream::binary); mapOut.serialization(outFile); //反序列化 MyMap mapIn; std::ifstream inFile("Seri.bin", std::ofstream::binary); mapIn.unserialization(inFile); getchar(); return 0; }
非浸入式序列化:如果想要序列化的非C++标准类我们不能修改它,则可以使用非浸入式序列化:
#include <fstream> #include "boost/archive/binary_oarchive.hpp" #include "boost/archive/binary_iarchive.hpp" #include <boost/serialization/map.hpp> class MyMap { public: std::map<int, std::string> mapData; int size; }; void serialization(std::ofstream& ostream, MyMap & p, const unsigned int version) //序列化 { boost::archive::binary_oarchive oa(ostream); oa & p.mapData; oa & p.size; } void unserialization(std::ifstream& istream, MyMap & p, const unsigned int version) //反序列化 { boost::archive::binary_iarchive ia(istream); ia & p.mapData; ia & p.size; } int main() { //序列化 MyMap mapDataOut; mapDataOut.mapData = { {1, "item1"}, {2, "item2"} }; mapDataOut.size = mapDataOut.mapData.size(); std::ofstream FileOut("Data.bin", std::ofstream::binary); serialization(FileOut, mapDataOut, 1); //反序列化 MyMap mapDataIn; std::ifstream FileIn("Data.bin", std::ifstream::binary); unserialization(FileIn, mapDataIn, 1); getchar(); return 0; }