首页 > 编程语言 >C++ | 关联容器map通过值(Value)找键(Key)

C++ | 关联容器map通过值(Value)找键(Key)

时间:2022-10-14 20:55:46浏览次数:35  
标签:std map key Val Value item Key find

今天又学到了一个关于关联容器map小技巧:通过值(Value)来寻找对应的键(Key),这个功能通过std::find_if实现,代码如下

template <class T, class U> T findKeyByValue(const U Val, const std::map<T, U>& map_)
{
    auto find_item = std::find_if(map_.begin(), map_.end(),
                                  [Val](const auto& item) { return item.second == Val; });
    //
    T key;
    if (find_item != map_.end())
    {
        key = (*find_item).first;
    }

    return key;
}

测试代码如下:

#include <iostream>
#include <map>
#include <algorithm>

template <class T, class U> T findKeyByValue(const U Val, const std::map<T, U>& map_)
{
    auto find_item = std::find_if(map_.begin(), map_.end(),
                                  [Val](const auto& item) { return item.second == Val; });
    //
    T key;
    if (find_item != map_.end())
    {
        key = (*find_item).first;
    }

    return key;
}

int main(int argc, char* argv[])
{
    std::map<std::string, int> test_map{{"A", 65}, {"B", 66}, {"C", 67}};
    int value = 66;
    std::cout << findKeyByValue(value, test_map) << std::endl;

    return 0;
}

可以看到输出结果为值66对应的键B

image

标签:std,map,key,Val,Value,item,Key,find
From: https://www.cnblogs.com/Fitanium/p/16792982.html

相关文章

  • 操作系统导论习题解答(31. Semaphores)
    Semaphores带着问题学习:如何使用信号量(semaphores)?1.Semaphores:ADefinitionsemaphore是一个具有整数值的对象,可以使用两个例程来对其进行操作。POSIX中两个例程为se......
  • [Typescript] 50. Medium - RequiredByKeys
    Implementageneric RequiredByKeys<T,K> whichtakestwotypeargument T and K.K specifythesetofpropertiesof T thatshouldsettoberequired.Wh......
  • [Typescript] 49. Medium - PartialByKeys
    Implementageneric PartialByKeys<T,K> whichtakestwotypeargument T and K.K specifythesetofpropertiesof T thatshouldsettobeoptional.Whe......
  • Fixed Value Append
    ForDomains,appendscanbecreatedforFixedValues.Afixedvalueappendisassignedtoexactlyonedomain.Adomaincanhavemultiplefixedvalueappends.Fix......
  • 解决 Optional int parameter 'postId' is present but cannot be translated into a
    问题:在构造函数中传入整型的postId属性后报错,错误如下:Optionalintparameter'postId'ispresentbutcannotbetranslatedintoanullvalueduetobeingdeclared......
  • MAPPO学习笔记(2) —— 从MAPPO论文入手
    在有了上一节一些有关PPO算法的概念作为基础后,我们就可以正式开始对于MAPPO这一算法的学习。那么,既然要学习一个算法,就不得不去阅读提出这一算法的论文。那么本篇博客将从......
  • SpringBoot中Server层以及Mapper层常用注解
    4.Service层注解@Service注解一般写在业务层的接口实现类上,而不是接口上。4.1@Service@Service:@Service注解用于类上,标记当前类是一个service类,加上该注解会将当......
  • Tampermonkey 插件
    一简介​每次使用搜索引擎进行内容检索的时候,经常会搜索到一些带有广告的页面,而这些内容往往不是我们所需要的,这些内容统称为干扰项,那如何在使用搜索引擎内容检索时排除......
  • CF1195E OpenStreetMap
    题目传送门思路单调队列板子。设\(b_{i,j}\)表示第\(i\)行,区间为\(j\)到\(j+y-1\)的最小值,不难发现这个可以用单调队列\(O(nm)\)预处理出来。接下来我们的问......
  • 【转】outlook配置腾讯企业邮箱(腾讯企业邮箱imap服务器地址)
     原文:https://www.zhangshilong.cn/work/12043.html ------------------ 以Outlook2016为例。步骤1,在开始菜单中,打开Outlook程序。步骤2,单击[下一步]步骤3,单......