环境:vs2010
该方式不会因为使用std::map[key] 这种操作而无缘无故插入了一个key。可放心使用。(请确保value的类型有operator == 比较的能力)
包含头文件:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <map>
#include <algorithm>
#include <string>
检查一个std::map对象是否有自定的key值函数(两种处理):
//方式1,使用algorithm的算法库
template<typename T_KEY, typename T_VALUE>
bool HasMapKey_1(std::map<T_KEY, T_VALUE>& tMap, T_KEY tKey)
{
std::map<T_KEY, T_VALUE>::iterator it = std::find_if(tMap.begin(), tMap.end(), [tKey](std::pair<T_KEY, T_VALUE> p)->bool{
if(p.first == tKey)
{
return true;
}
return false;
});
return it != tMap.end();
}
//方式2,使用map自带的查找函数
template<typename T_KEY, typename T_VALUE>
bool HasMapKey_2(std::map<T_KEY, T_VALUE>& tMap, T_KEY tKey)
{
std::map<T_KEY, T_VALUE>::iterator it = tMap.find(tKey);
return it != tMap.end();
}
使用方式:
int main(int argc, char** argv)
{
typedef std::map<std::string , int> DiyMap;
DiyMap m;
m["A"] = 1;
m["B"] = 1;
m["C"] = 1;
bool hasB_1 = HasMapKey_1<std::string, int>(m, "A");
bool hasB_2 = HasMapKey_2<std::string, int>(m, "A");
bool hasD_1 = HasMapKey_1<std::string, int>(m, "D");
bool hasD_2 = HasMapKey_2<std::string, int>(m, "D");
printf("haseB_1(%d),haseB_2(%d),haseD_1(%d),haseD_2(%d)\n", hasB_1, hasB_2, hasD_1, hasD_2);
system("pause");
return 0;
}
结果: