Search code examples
booststldictionarytraversalbimap

How to traverse a map by value


Say there is a map: typedef map<int, string> MyMap;

I'd like to traverse it by the string, for example:

3 -> a
1 -> b
7 -> b
2 -> c

One way is to sort this map by its value. But I'm afraid this will have impact to find() efficiency (is it true?)

Another choice is to use boost::bimap. But, as you might notice, the value in MyMap is not unique, so bimap is not applicable here.

Is there a good way to do it?


Solution

  • I found a solution to use multiple values in boost.bimap: multiset_of

    The data definition changed to:

    #include <boost/bimap/multiset_of.hpp>
    typedef boost::bimap<int, boost::bimaps::multiset_of<std::string> > MyMap;
    

    Now I can traverse my data by either key or value.