Find mapped value of map

2019-01-23 01:27发布

Is there a way in C++ to search for the mapped value (instead of the key) of a map, and then return the key? Usually, I do someMap.find(someKey)->second to get the value, but here I want to do the opposite and obtain the key (the values and keys are all unique).

5条回答
迷人小祖宗
2楼-- · 2019-01-23 01:58

We can create a reverseMap which maps values to keys.

Like,

map<key, value>::iterator it;
map<value, key> reverseMap;

for(it = originalMap.begin(); it != originalMap.end(); it++)
     reverseMap[it->second] = it->first;

This also is basically like a linear search but will be useful if you have a number of queries.

查看更多
一纸荒年 Trace。
3楼-- · 2019-01-23 01:59

What you're looking for is a Bimap, and there is an implementation of it available in Boost: http://www.boost.org/doc/libs/1_36_0/libs/bimap/doc/html/index.html

查看更多
爷、活的狠高调
4楼-- · 2019-01-23 02:20

Because of how a map is designed, you'll need to do the equivalent of a search on unordered data.

for (it = someMap.begin(); it != someMap.end(); ++it )
    if (it->second == someValue)
        return it->first;
查看更多
forever°为你锁心
5楼-- · 2019-01-23 02:20
struct test_type
{
    CString str;
    int n;
};


bool Pred( std::pair< int, test_type > tt )
{
    if( tt.second.n == 10 )
        return true;

    return false;
}


std::map< int, test_type > temp_map;

for( int i = 0; i < 25; i++ )

{
    test_type tt;
    tt.str.Format( _T( "no : %d" ), i );
    tt.n = i;

    temp_map[ i ] = tt;
}

auto iter = std::find_if( temp_map.begin(), temp_map.end(), Pred );
查看更多
姐就是有狂的资本
6楼-- · 2019-01-23 02:21

Using lambdas (C++11 and newer)

//A MAP OBEJCT
std::map<int, int> mapObject;

//INSERT VALUES
mapObject.insert(make_pair(1, 10));
mapObject.insert(make_pair(2, 20));
mapObject.insert(make_pair(3, 30));
mapObject.insert(make_pair(4, 40));

//FIND KEY FOR BELOW VALUE
int val = 20;

auto result = std::find_if(
          mapObject.begin(),
          mapObject.end(),
          [val](const auto& mo) {return mo.second == val; });

//RETURN VARIABLE IF FOUND
if(result != mapObject.end())
    int foundkey = result->first;
查看更多
登录 后发表回答