转载:http://www.cnblogs.com/xufeiyang/archive/2012/05/09/2491871.html
CValueFind
1 #ifndef _CVALUEFIND_H_ 2 #define _CVALUEFIND_H_ 3 #include <string> 4 #include <algorithm> 5 #include <map> 6 7 8 class map_value_finder 9 { 10 public: 11 map_value_finder(const std::string &cmp_string):m_s_cmp_string(cmp_string){} 12 bool operator ()(const std::map<int, std::string>::value_type &pair) 13 { 14 return pair.second == m_s_cmp_string; 15 } 16 private: 17 const std::string &m_s_cmp_string; 18 }; 19 #endif
main
#include <iostream> #include <windows.h> #include <vector> #include "CValueFind.h" using namespace std; //map按value值查找——find_if的使用 int main() { std::map<int, 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(31, "english")); my_map.insert(std::make_pair(32, "english")); my_map.insert(std::make_pair(33, "english")); my_map.insert(std::make_pair(34, "english")); my_map.insert(std::make_pair(35, "english")); my_map.insert(std::make_pair(36, "english")); my_map.insert(std::make_pair(37, "english")); my_map.insert(std::make_pair(38, "english")); my_map.insert(std::make_pair(39, "english")); my_map.insert(std::make_pair(40, "hongkong")); std::map<int, std::string>::iterator it = my_map.end(); 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:%d value:%s\n", it->first, it->second.c_str()); } getchar(); return 0; }
时间: 2024-11-05 02:38:25