map如何通过value值找到key

16 篇文章 7 订阅

在map中根据key寻找value比较方便,但是如果根据value去寻找key就比较麻烦一点,尤其是多个key对应同一个value时,本文介绍通过find_if、 find系列函数去寻找,在key-value是一一对应关系时,这个办法比较管用,现介绍如下:

#include <iostream>
#include <map>
#include <stdio.h>
#include <algorithm>
#include <string>

bool value_to_key( std::map<int,std::string> ::value_type item)
{
    if(item.second == "1")
    {
        printf("%d \n",item.first);
        return true;

    }
    else
    {
        return false;
    }

}

class map_value_finder
{
public:
    map_value_finder(const std::string &cmp_string):m_s_cmp_string(cmp_string)
    {
        printf("%s(%d)\n",__FUNCTION__,__LINE__);
    };
    bool operator ()(const std::map<int, std::string>::value_type &pair)
    {
        printf("%s(%d)\n",__FUNCTION__,__LINE__);
        return pair.second == m_s_cmp_string;
    }
private:
    const std::string &m_s_cmp_string;                    
};

int main()
{
    std::string target = "1";
    std::map<int,std::string> map_test;
    map_test.insert(std::make_pair(5, "1"));
    map_test.insert(std::make_pair(2, "2"));
    map_test.insert(std::make_pair(3, "3"));
    map_test.insert(std::make_pair(4, "4"));

    //根据value 找key lambda方式
    auto it = std::find_if(map_test.begin(),map_test.end(),[target](const std::map<int, std::string>::value_type item )->bool{return item.second == target;});
    printf("%d \n",it->first);

    //根据value 找key 函数方式
    auto it1 = std::find_if(map_test.begin(),map_test.end(),value_to_key);
    printf("%d \n",it1->first);
    //根据value 找key 对象的方式 通过打印来确定 map_value_finder("1")的工作方式
    auto it2 = std::find_if(map_test.begin(),map_test.end(),map_value_finder("1"));
    printf("%d \n",it2->first);
    map_value_finder temp1("2");
    bool temp = temp1((std::make_pair(5, "1")));

}

 

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值