Search for specific value in std::map [duplicate]
Possible Duplicates:
Checking value exist in a std::map - C++ How to traverse a stl map/vector/list/etc?
Hello,
Is it possible to search for specific value in std::map, not knowing the key? I know I could iterate over whole map, and compare values, but it is possible to do using a function from std algorithms?
Well, you could use std::find_if
:
int main()
{
typedef std::map<int, std::string> my_map;
my_map m;
m.insert(std::make_pair(0, "zero"));
m.insert(std::make_pair(1, "one"));
m.insert(std::make_pair(2, "two"));
const std::string s("one");
const my_map::const_iterator it = std::find_if(
m.begin(), m.end(), boost::bind(&my_map::value_type::second, _1) == s
);
}
But that's just slightly better than a hand-crafted loop : it's still O(n)
.
You could use Boost.Bimap if you want to index on values as well as keys. Without this or similar, this will have to be done by brute force (=> scan the map
by hand).
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.
Will this help? STL find_if
You need to have some sort of predicate, either a function pointer or an object with operator()
implemented. Said predicate should take just one parameter.
There are (awkward) ways to do this using standard functions (e.g., std::find_if
), but these still involve iterating over the whole map. Boost.Bimap will provide efficient indexing in both directions, and you can go even further with Boost.Multi-Index.
精彩评论