代码之家  ›  专栏  ›  技术社区  ›  wrongusername

查找映射值

  •  33
  • wrongusername  · 技术社区  · 15 年前

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

    6 回复  |  直到 9 年前
        1
  •  40
  •   Bill Lynch    7 年前

    因为 map 在设计时,您将需要对无序数据执行相当于搜索的操作。

    for (auto it = someMap.begin(); it != someMap.end(); ++it)
        if (it->second == someValue)
            return it->first;
    
        2
  •  15
  •   Rajesh Negi    7 年前

    使用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;
    
        3
  •  10
  •   Paul    15 年前

    你要找的是一个Bimap,Boost中提供了它的一个实现: http://www.boost.org/doc/libs/1_36_0/libs/bimap/doc/html/index.html

        4
  •  2
  •   Karan Saxena    8 年前

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

    就像,

    map<key, value>::iterator it;
    map<value, key> reverseMap;
    
    for(it = originalMap.begin(); it != originalMap.end(); it++)
         reverseMap[it->second] = it->first;
    

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

        5
  •  2
  •   lubgr    7 年前

    因为这还没有被提及:结构化绑定(可以从C++ 17提供)使得编写一个相同的循环的便捷方法如图中所示。 Bill Lynch's answer ,即。

    for (const auto& [key, value] : someMap)
        if (value == someValue)
            return key;
    
        6
  •  0
  •   이원용    9 年前
    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 );