tagged_bidirectional_map.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. // Boost.Bimap Example
  9. //-----------------------------------------------------------------------------
  10. // This example shows how to construct a bidirectional map with
  11. // multi_index_container.
  12. // By a bidirectional map we mean a container of elements of
  13. // std::pair<const FromType,const ToType> such that no two elements exists with
  14. // the same first or second value (std::map only guarantees uniqueness of the
  15. // first member).
  16. // Fast lookup is provided for both keys. The program features a tiny
  17. // Spanish-English dictionary with online query of words in both languages.
  18. //[ code_mi_to_b_path_tagged_bidirectional_map
  19. #include <iostream>
  20. #include <boost/bimap/bimap.hpp>
  21. using namespace boost::bimaps;
  22. // tags
  23. struct spanish {};
  24. struct english {};
  25. // A dictionary is a bidirectional map from strings to strings
  26. typedef bimap
  27. <
  28. tagged< std::string,spanish >, tagged< std::string,english >
  29. > dictionary;
  30. typedef dictionary::value_type translation;
  31. int main()
  32. {
  33. dictionary d;
  34. // Fill up our microdictionary.
  35. // first members Spanish, second members English.
  36. d.insert( translation("hola" ,"hello" ));
  37. d.insert( translation("adios","goodbye"));
  38. d.insert( translation("rosa" ,"rose" ));
  39. d.insert( translation("mesa" ,"table" ));
  40. std::cout << "enter a word" << std::endl;
  41. std::string word;
  42. std::getline(std::cin,word);
  43. // search the queried word on the from index (Spanish) */
  44. dictionary::map_by<spanish>::const_iterator it =
  45. d.by<spanish>().find(word);
  46. if( it != d.by<spanish>().end() )
  47. {
  48. std::cout << word << " is said "
  49. << it->get<english>() << " in English" << std::endl;
  50. }
  51. else
  52. {
  53. // word not found in Spanish, try our luck in English
  54. dictionary::map_by<english>::const_iterator it2 =
  55. d.by<english>().find(word);
  56. if( it2 != d.by<english>().end() )
  57. {
  58. std::cout << word << " is said "
  59. << it2->get<spanish>() << " in Spanish" << std::endl;
  60. }
  61. else
  62. {
  63. std::cout << "No such word in the dictionary" << std::endl;
  64. }
  65. }
  66. return 0;
  67. }
  68. //]