Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for specific value in std::map [duplicate]

Tags:

c++

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?

like image 457
BЈовић Avatar asked Dec 06 '10 15:12

BЈовић


4 Answers

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).

like image 104
icecrime Avatar answered Nov 17 '22 08:11

icecrime


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.

like image 40
Platinum Azure Avatar answered Nov 17 '22 09:11

Platinum Azure


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.

like image 39
Steve Townsend Avatar answered Nov 17 '22 08:11

Steve Townsend


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.

like image 2
Marcelo Cantos Avatar answered Nov 17 '22 08:11

Marcelo Cantos