1. 程式人生 > >測試了下boost的序列化反序列化功能

測試了下boost的序列化反序列化功能

con != bar lan class try hat out ora

[cpp] view plain copy
  1. // testSerialization.cpp : Defines the entry point for the console application.
  2. //
  3. #include "stdafx.h"
  4. #include <boost/archive/text_oarchive.hpp>
  5. #include <boost/archive/text_iarchive.hpp>
  6. #include <boost/serialization/vector.hpp>
  7. #include <string>
  8. #include <vector>
  9. #include <iostream>
  10. #include <sstream>
  11. #include <fstream>
  12. /*
  13. 標題:boost的序列化反序列化功能測試
  14. 環境:VS2010sp1、boost 1.55
  15. 參考資料:
  16. [1]《Boost中支持序列化反序列化的庫--boost.serialization 》
  17. http://blog.csdn.net/oracleot/article/details/4280084
  18. [2]《What does BOOST_SERIALIZATION_NVP do when serializing object?》
  19. http://stackoverflow.com/questions/8532331/what-does-boost-serialization-nvp-do-when-serializing-object
  20. */
  21. struct MyRecord
  22. {
  23. std::string a;
  24. std::string b;
  25. //為使當前的結構能支持序列化,得加入下面的代碼段
  26. private:
  27. friend class boost::serialization::access;
  28. template<class Archive>
  29. void serialize(Archive & ar, const unsigned int version)
  30. {
  31. ar & a;
  32. ar & b;
  33. }
  34. };
  35. struct MyData{
  36. int id;
  37. std::string strName;
  38. std::string strValue;
  39. MyData() {}
  40. MyData(int id, std::string strName, std::string strValue)
  41. {
  42. this->id = id;
  43. this->strName = strName;
  44. this->strValue = strValue;
  45. }
  46. std::vector<MyRecord> listMR;
  47. private:
  48. friend boost::serialization::access; //聲明友元,授予訪問權限
  49. template<typename Archive>
  50. void serialize(Archive &ar,const unsigned int version) //序列化函數
  51. {
  52. ar & id;
  53. ar & strName & strValue;
  54. ar & listMR;
  55. }
  56. };
  57. void printTest(MyData &mt)
  58. {
  59. std::cout<<"a="<<mt.id<<" uid="<<mt.strName.c_str()<<" usr="<<mt.strValue.c_str()<<std::endl;
  60. std::vector<MyRecord>::iterator iter = mt.listMR.begin();
  61. while(iter!=mt.listMR.end())
  62. {
  63. std::cout<<"=> "<<iter->a.c_str()<<" "<<iter->b.c_str()<<std::endl;
  64. iter++;
  65. }
  66. }
  67. int _tmain(int argc, _TCHAR* argv[])
  68. {
  69. std::stringstream ss;
  70. //序列化
  71. MyData p1(11,"anderson","neo"); //被序列化的對象
  72. //為被序列化對象添加兩條記錄
  73. MyRecord mr,mr2;
  74. mr.a="apple",mr.b="第一條記錄";
  75. mr2.a = "this is b",mr2.b = "第二條記錄";
  76. p1.listMR.push_back(mr);
  77. p1.listMR.push_back(mr2);
  78. boost::archive::text_oarchive(ss) << p1; //序列化
  79. //序列化為xml形式要求中文為utf-8編碼,否則打開文件是亂碼
  80. //std::stringstream ss;
  81. //std::ofstream ofs("d:\\a.xml");
  82. //boost::archive::xml_oarchive oa(ofs);
  83. //oa << BOOST_SERIALIZATION_NVP(p1);
  84. //反序列化
  85. MyData p2; //被反序列化的對象
  86. boost::archive::text_iarchive(ss) >> p2; //反序列化
  87. printTest(p2);
  88. std::cout << "序列化後的=>" << ss.str() << std::endl;;
  89. return 0;
  90. }

http://blog.csdn.net/lee353086/article/details/38421095

測試了下boost的序列化反序列化功能