测试了下boost的序列化反序列化功能
2014-08-07 16:33
357 查看
// testSerialization.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/vector.hpp> #include <string> #include <vector> #include <iostream> #include <sstream> #include <fstream> /* 标题:boost的序列化反序列化功能测试 环境:VS2010sp1、boost 1.55 参考资料: [1]《Boost中支持序列化反序列化的库--boost.serialization 》 http://blog.csdn.net/oracleot/article/details/4280084 [2]《What does BOOST_SERIALIZATION_NVP do when serializing object?》 http://stackoverflow.com/questions/8532331/what-does-boost-serialization-nvp-do-when-serializing-object */ struct MyRecord { std::string a; std::string b; //为使当前的结构能支持序列化,得加入下面的代码段 private: friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & a; ar & b; } }; struct MyData{ int id; std::string strName; std::string strValue; MyData() {} MyData(int id, std::string strName, std::string strValue) { this->id = id; this->strName = strName; this->strValue = strValue; } std::vector<MyRecord> listMR; private: friend boost::serialization::access; //声明友元,授予访问权限 template<typename Archive> void serialize(Archive &ar,const unsigned int version) //序列化函数 { ar & id; ar & strName & strValue; ar & listMR; } }; void printTest(MyData &mt) { std::cout<<"a="<<mt.id<<" uid="<<mt.strName.c_str()<<" usr="<<mt.strValue.c_str()<<std::endl; std::vector<MyRecord>::iterator iter = mt.listMR.begin(); while(iter!=mt.listMR.end()) { std::cout<<"=> "<<iter->a.c_str()<<" "<<iter->b.c_str()<<std::endl; iter++; } } int _tmain(int argc, _TCHAR* argv[]) { std::stringstream ss; //序列化 MyData p1(11,"anderson","neo"); //被序列化的对象 //为被序列化对象添加两条记录 MyRecord mr,mr2; mr.a="apple",mr.b="第一条记录"; mr2.a = "this is b",mr2.b = "第二条记录"; p1.listMR.push_back(mr); p1.listMR.push_back(mr2); boost::archive::text_oarchive(ss) << p1; //序列化 //序列化为xml形式要求中文为utf-8编码,否则打开文件是乱码 //std::stringstream ss; //std::ofstream ofs("d:\\a.xml"); //boost::archive::xml_oarchive oa(ofs); //oa << BOOST_SERIALIZATION_NVP(p1); //反序列化 MyData p2; //被反序列化的对象 boost::archive::text_iarchive(ss) >> p2; //反序列化 printTest(p2); std::cout << "序列化后的=>" << ss.str() << std::endl;; return 0; }
相关文章推荐
- 测试了下boost的序列化反序列化功能
- AVL树(附加序列化和反序列化功能)
- 对java序列化和反序列化的理解和测试
- Boost中支持序列化反序列化的库--boost.serialization
- [置顶] boost如何序列化 和反序列化 指针类(本身类也可以)
- std::map容器序列化、反序列化测试
- javascript实现json的序列化和反序列化功能
- Boost中支持序列化反序列化的库--boost.serialization
- JS实现json的序列化和反序列化功能示例
- boost序列化补充说明
- [原创]FlashActionScript序列化和反序列化的实现(第一版)
- .Net 中序列化和反序列化应注意的事项
- 测试一下DasBlog的异站同步功能
- C#实现对象的Xml格式序列化及反序列化
- Asp.Net Forums中对.Net中序列化和反序列化的应用
- CnBlogs.Com用到的CSS控制的代码折叠功能测试
- Asp.Net Forums中对.Net中序列化和反序列化的应用
- 365Key兴趣小组功能开始测试
- Asp.Net Forums中对.Net中序列化和反序列化的应用
- 测试系统扫描的功能