简体   繁体   中英

How can I find out if a map contains a given value?

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM