serialization.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Boost.Bimap
  2. //
  3. // Copyright (c) 2006-2007 Matias Capeletto
  4. //
  5. // Distributed under the Boost Software License, Version 1.0.
  6. // (See accompanying file LICENSE_1_0.txt or copy at
  7. // http://www.boost.org/LICENSE_1_0.txt)
  8. // VC++ 8.0 warns on usage of certain Standard Library and API functions that
  9. // can be cause buffer overruns or other possible security issues if misused.
  10. // See https://web.archive.org/web/20071014014301/http://msdn.microsoft.com/msdnmag/issues/05/05/SafeCandC/default.aspx
  11. // But the wording of the warning is misleading and unsettling, there are no
  12. // portable alternative functions, and VC++ 8.0's own libraries use the
  13. // functions in question. So turn off the warnings.
  14. #define _CRT_SECURE_NO_DEPRECATE
  15. #define _SCL_SECURE_NO_DEPRECATE
  16. // Boost.Bimap Example
  17. //-----------------------------------------------------------------------------
  18. #include <boost/config.hpp>
  19. #include <fstream>
  20. #include <string>
  21. #include <cassert>
  22. #include <boost/bimap/bimap.hpp>
  23. #include <boost/archive/text_oarchive.hpp>
  24. #include <boost/archive/text_iarchive.hpp>
  25. using namespace boost::bimaps;
  26. int main()
  27. {
  28. //[ code_bimap_and_boost_serialization
  29. typedef bimap< std::string, int > bm_type;
  30. // Create a bimap and serialize it to a file
  31. {
  32. bm_type bm;
  33. bm.insert( bm_type::value_type("one",1) );
  34. bm.insert( bm_type::value_type("two",2) );
  35. std::ofstream ofs("data");
  36. boost::archive::text_oarchive oa(ofs);
  37. oa << const_cast<const bm_type&>(bm); /*<
  38. We must do a const cast because Boost.Serialization archives
  39. only save const objects. Read Boost.Serializartion docs for the
  40. rationale behind this decision >*/
  41. /*<< We can only serialize iterators if the bimap was serialized first.
  42. Note that the const cast is not requiered here because we create
  43. our iterators as const. >>*/
  44. const bm_type::left_iterator left_iter = bm.left.find("two");
  45. oa << left_iter;
  46. const bm_type::right_iterator right_iter = bm.right.find(1);
  47. oa << right_iter;
  48. }
  49. // Load the bimap back
  50. {
  51. bm_type bm;
  52. std::ifstream ifs("data", std::ios::binary);
  53. boost::archive::text_iarchive ia(ifs);
  54. ia >> bm;
  55. assert( bm.size() == 2 );
  56. bm_type::left_iterator left_iter;
  57. ia >> left_iter;
  58. assert( left_iter->first == "two" );
  59. bm_type::right_iterator right_iter;
  60. ia >> right_iter;
  61. assert( right_iter->first == 1 );
  62. }
  63. //]
  64. return 0;
  65. }