61

C++ 中有没有办法搜索映射的映射值(而不是键),然后返回键?通常,我这样做是someMap.find(someKey)->second为了获取值,但在这里我想做相反的事情并获取键(值和键都是唯一的)。

4

6 回答 6

67

由于 amap的设计方式,您需要对无序数据进行等效的搜索。

for (auto it = someMap.begin(); it != someMap.end(); ++it)
    if (it->second == someValue)
        return it->first;
于 2010-11-24T05:08:35.237 回答
27

使用 lambdas(C++11 和更新版本)

//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;
于 2018-06-02T00:05:23.977 回答
16

如果您经常在较大的地图中进行这种搜索,那么查看 Bimap 可能会很有趣,它将同时索引键和值。Boost 中有一个 Bimap 的实现:https ://www.boost.org/doc/libs/1_77_0/libs/bimap/doc/html/index.html

于 2010-11-24T05:09:40.213 回答
14

结构化绑定(自 C++17 起可用)提供了一种方便的方式来编写与比尔林奇的回答中描述的相同的循环,即

for (const auto& [key, value] : someMap)
    if (value == someValue)
        return key;
于 2019-03-13T08:20:53.107 回答
6

我们可以创建一个将值映射到键的 reverseMap。

像,

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

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

这也基本上类似于线性搜索,但如果您有多个查询,这将很有用。

于 2017-11-23T19:43:25.003 回答
1
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 );
于 2017-01-06T07:47:02.530 回答