c++使用cereal序列化库保存文件并恢复原始数据结构

27 篇文章 2 订阅
本文介绍了如何利用C++的cereal库将自定义数据类型保存为JSON文件并恢复。首先包含了cereal的头文件,然后定义了多个结构体,接着为这些结构体添加了序列化和反序列化的函数模板。之后,提供了保存和加载数据的函数,分别使用JSONOutputArchive和JSONInputArchive进行操作。示例展示了如何处理MatchResult结构体及其包含的数据成员。
摘要由CSDN通过智能技术生成

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;
}

参考博客

https://blog.csdn.net/sunnyloves/article/details/51373793

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值