c++使用cereal序列化库保存文件并恢复原始数据结构
根据官方文档介绍,cereal是一个只有头文件的C++序列化库,它能够将任何数据类型转换为二进制编码或是xml文件或是json文件,也可以将转换后的文件恢复成原来的数据结构。cereal被设计为快速、轻量和易于扩展的,同时其不依赖任何其他第三方库,因此可以非常容易被已有的工程所使用。
cereal库使用
本节介绍如何将自己定义的数据类型保存为json文件
1.包含头文件
#include <cereal/archives/JSON.hpp>
#include <cereal/cereal.hpp>
#include <cereal/types/vector.hpp>
2.定义我自己的结构体
typedef struct tagFPT
{
float x,y;
}FPT;
typedef struct tagFPT3D
{
float x,y,z;
}FPT3D;
typedef struct tagFPT4D
{
float xl,yl,xr,yr;
}FPT4D;
struct MatchResult {//一个点
FPT3D XYZ;//地面控制点
//int ptId;
vector<int> id_img;
vector<FPT> pt_dom;
vector<FPT> pt_src;
int id_ref;
FPT4D pt_ref;
};
using MatchResults = std::vector<MatchResult>;
3.添加函数模板
namespace cereal {
template <class Archive> inline void serialize(Archive& ar,FPT& m) {
ar(make_nvp("x", m.x));
ar(make_nvp("y", m.y));
}
template <class Archive> inline void serialize(Archive& ar, FPT3D& m) {
ar(make_nvp("X", m.x));
ar(make_nvp("Y", m.y));
ar(make_nvp("Z", m.z));
}
template <class Archive> inline void serialize(Archive& ar, FPT4D& m) {
ar(make_nvp("xl", m.xl));
ar(make_nvp("yl", m.yl));
ar(make_nvp("xr", m.xr));
ar(make_nvp("yr", m.yr));
}
template <class Archive> inline void serialize(Archive& ar, MatchResult& m) {
ar(make_nvp("Position", m.XYZ));
ar(make_nvp("refDomId", m.id_ref));
ar(make_nvp("refDomPt", m.pt_ref));
ar(make_nvp("photoIds", m.id_img));
ar(make_nvp("photodomPts", m.pt_dom));
ar(make_nvp("photoPts", m.pt_src));
}
}
4.添加保存函数
void saveMatchRes(const MatchResults& match, const std::string& path) {
/*ofstream ofile(path, ios::binary);
cereal::PortableBinaryOutputArchive ar(ofile);*/
ofstream ofile(path);
cereal::JSONOutputArchive ar(ofile);
ar(match);
}
5.添加读取函数
MatchResults loadMatchRes(const std::string& path) {
/* std::ifstream ifile(path, std::ios::binary);
cereal::PortableBinaryInputArchive ar(ifile);*/
ifstream ifile(path);
cereal::JSONInputArchive ar(ifile);
MatchResults m;
ar(m);
return m;
}