bidirectional_map.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. #include <boost/config.hpp>
  19. //[ code_mi_to_b_path_bidirectional_map
  20. #include <iostream>
  21. #include <boost/tokenizer.hpp>
  22. #include <boost/bimap/bimap.hpp>
  23. using namespace boost::bimaps;
  24. // A dictionary is a bidirectional map from strings to strings
  25. typedef bimap<std::string,std::string> dictionary;
  26. typedef dictionary::value_type translation;
  27. int main()
  28. {
  29. dictionary d;
  30. // Fill up our microdictionary.
  31. // first members Spanish, second members English.
  32. d.insert( translation("hola" ,"hello" ));
  33. d.insert( translation("adios","goodbye"));
  34. d.insert( translation("rosa" ,"rose" ));
  35. d.insert( translation("mesa" ,"table" ));
  36. std::cout << "enter a word" << std::endl;
  37. std::string word;
  38. std::getline(std::cin,word);
  39. // search the queried word on the from index (Spanish)
  40. dictionary::left_const_iterator it = d.left.find(word);
  41. if( it != d.left.end() )
  42. {
  43. // the second part of the element is the equivalent in English
  44. std::cout << word << " is said "
  45. << it->second /*< `it` is an iterator of the left view, so
  46. `it->second` refers to the right element of
  47. the relation, the word in english >*/
  48. << " in English" << std::endl;
  49. }
  50. else
  51. {
  52. // word not found in Spanish, try our luck in English
  53. dictionary::right_const_iterator it2 = d.right.find(word);
  54. if( it2 != d.right.end() )
  55. {
  56. std::cout << word << " is said "
  57. << it2->second /*< `it2` is an iterator of the right view, so
  58. `it2->second` refers to the left element of
  59. the relation, the word in spanish >*/
  60. << " in Spanish" << std::endl;
  61. }
  62. else
  63. {
  64. std::cout << "No such word in the dictionary" << std::endl;
  65. }
  66. }
  67. return 0;
  68. }
  69. //]