1

I'd like to find out whether a given value is present in a map. Also getting the corresponding key(s) would be nice but is not required.

bool map::contains(string value);

Is there a simple way to do this other than to iterate over the whole map and comparing each value with the given value? Why is there no corresponding method in the STL?

Fabian
  • 4,001
  • 4
  • 28
  • 59

1 Answers1

6

std::map only indexes its elements by key; it does not index them by value. Therefore, there is no way to look up an element by its value without iterating over the map.

Take a look at Boost.Bimap:

Boost.Bimap is a bidirectional maps library for C++. With Boost.Bimap you can create associative containers in which both types can be used as key. A bimap<X,Y> can be thought of as a combination of a std::map<X,Y> and a std::map<Y,X>.

Using it is pretty straightforward, although you will of course need to consider the question of whether duplicate values are allowed.

Also, see Is there a Boost.Bimap alternative in c++11?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012