#include <map>
#include <string>
#include <algorithm>
using namespace std;
class map_value_finder
{
public:
map_value_finder(const std::string &cmp_string):m_s_cmp_string(cmp_string){}
bool operator ()(const std::map<std::string, std::string>::value_type &pair)
{
return pair.second == m_s_cmp_string;
}
private:
const std::string &m_s_cmp_string;
};
int main()
{
std::map<std::string, std::string> my_map;
my_map.insert(std::make_pair("10", "china"));
my_map.insert(std::make_pair("20", "usa"));
my_map.insert(std::make_pair("30", "english"));
my_map.insert(std::make_pair("40", "hongkong"));
//通过key查找
std::map<string, std::string>::iterator it = my_map.find("10");
if (it == my_map.end())
printf("not found\n");
else
printf("found key:%s value:%s\n", it->first.c_str(), it->second.c_str());
//通过value查找
it = std::find_if(my_map.begin(), my_map.end(), map_value_finder("english"));
if (it == my_map.end())
printf("not found\n");
else
printf("found key:%s value:%s\n", it->first.c_str(), it->second.c_str());
return 0;
}
运行结果: