c++ boost 序列化对象存储及其访问

本文介绍了一个使用Boost库进行对象序列化的C++示例程序。该程序定义了两个类A和IvNode,并演示了如何利用Boost.Serialization库将这些类的对象序列化到文本文件中,再从文件中反序列化出来。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参照下面的例子就可以完成。

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/vector.hpp>
#include<boost/serialization/bitset.hpp>

using namespace std;
using namespace cv;



using namespace std;
struct IvNode
{
    friend class boost::serialization::access;
	template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & docId;   //就是这么简单,也可以使用 ar<<a 这样的语法
        ar & x;
		ar & y;
		ar & scale;
		ar & orientation;
		ar& hecode;
    }
    unsigned int docId;
	float x;
	float y;
	float scale;
	float orientation;
	bitset<64>  hecode;
    bool operator<(const IvNode& other) const
    {
        return this->docId<other.docId;
    }
	bool operator==(const IvNode& other) const{
        return this->docId==other.docId;
	}
	void print(){
      cout<<docId<<" "<<x<<" "<<y<<" "<<scale<<" "<<orientation<<" "<<hecode<<endl;
	 }
};

class A
{
private:
    // 为了能让串行化类库能够访问私有成员,所以要声明一个友元类
    friend class boost::serialization::access;
    // 对象的数据
    int a;
    double b;
	vector<int> vec;
    // 串行化的函数,这一个函数完成对象的保存与恢复
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & a;   //就是这么简单,也可以使用 ar<<a 这样的语法
        ar & b;
		ar & vec;
    }
public:
    A(int aa,double bb):a(aa),b(bb){
       vec.push_back(2); vec.push_back(3);
	}
    A(){}
    void print(){std::cout<<a<<' '<<b<<" "<<vec[0]<<" "<<vec[1]<<endl;}
};   
int main()
{
   std::ofstream fout("file.txt");// 把对象写到file.txt文件中
   boost::archive::text_oarchive oa(fout); // 文本的输出归档类,使用一个ostream来构造
   IvNode node;
   node.docId=1;
    node.x=2;
   node.y=3;
   node.scale=20;
   node.orientation=3.12;
   node.hecode.reset();
   for(int i=0;i<64;++i)
   	if(i%2==0) node.hecode.set(i);
   oa<<node;
   node.x=3;
   oa<<node;
   fout.close();// 关闭文件
  
   std::ifstream fin("file.txt");
   boost::archive::text_iarchive ia(fin); // 文本的输入归档类
  IvNode newNode,newNode2;
  while((ia>>newNode)!=EOF){
    newNode.print();
  }
  
   fin.close();

   return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值