Find mapped value of map

两盒软妹~` 提交于 2019-11-27 20:00:50

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;
Pavan Chandaka

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;

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

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.

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

As this has not been mentioned yet: structured bindings (available since C++17) enable a convenient way of writing the same loop as depicted in Bill Lynch's answer, i.e.

for (const auto& [key, value] : someMap)
    if (value == someValue)
        return key;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!