在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")));
}