通用判断std::map对象是否存在key的模板函数

本文介绍了在C++中如何安全地检查std::map是否包含特定键值,避免因使用std::map[key]可能导致的意外插入。提供了两种方法:一种是利用algorithm库中的find_if算法,另一种是直接使用map的find成员函数。示例代码展示了这两种方法的实现及使用方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

环境: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;
}

 

 

结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值