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
9 /******************************************************************************
10 Boost.MultiIndex
11 ******************************************************************************/
12
13 #include <boost/config.hpp>
14
15 //[ code_mi_to_b_path_mi_bidirectional_map
16
17 #include <iostream>
18 #include <boost/tokenizer.hpp>
19
20 #include <boost/multi_index_container.hpp>
21 #include <boost/multi_index/key_extractors.hpp>
22 #include <boost/multi_index/ordered_index.hpp>
23
24 using namespace boost;
25 using namespace boost::multi_index;
26
27 // tags for accessing both sides of a bidirectional map
28
29 struct from {};
30 struct to {};
31
32 // The class template bidirectional_map wraps the specification
33 // of a bidirectional map based on multi_index_container.
34
35 template<typename FromType,typename ToType>
36 struct bidirectional_map
37 {
38 typedef std::pair<FromType,ToType> value_type;
39
40 typedef multi_index_container<
41 value_type,
42 indexed_by
43 <
44 ordered_unique
45 <
46 tag<from>, member<value_type,FromType,&value_type::first>
47 >,
48 ordered_unique
49 <
50 tag<to>, member<value_type,ToType,&value_type::second>
51 >
52 >
53
54 > type;
55
56 };
57
58 // A dictionary is a bidirectional map from strings to strings
59
60 typedef bidirectional_map<std::string,std::string>::type dictionary;
61
main()62 int main()
63 {
64 dictionary d;
65
66 // Fill up our microdictionary.
67 // first members Spanish, second members English.
68
69 d.insert(dictionary::value_type("hola","hello"));
70 d.insert(dictionary::value_type("adios","goodbye"));
71 d.insert(dictionary::value_type("rosa","rose"));
72 d.insert(dictionary::value_type("mesa","table"));
73
74 std::cout << "enter a word" << std::endl;
75 std::string word;
76 std::getline(std::cin,word);
77
78 // search the queried word on the from index (Spanish)
79
80 dictionary::iterator it = d.get<from>().find(word);
81
82 if( it != d.end() )
83 {
84 // the second part of the element is the equivalent in English
85
86 std::cout << word << " is said "
87 << it->second << " in English" << std::endl;
88 }
89 else
90 {
91 // word not found in Spanish, try our luck in English
92
93 dictionary::index_iterator<to>::type it2 = d.get<to>().find(word);
94 if( it2 != d.get<to>().end() )
95 {
96 std::cout << word << " is said "
97 << it2->first << " in Spanish" << std::endl;
98 }
99 else
100 {
101 std::cout << "No such word in the dictionary" << std::endl;
102 }
103 }
104
105 return 0;
106 }
107 //]
108