C++中map查找元素是否存在的3种方式

1. map[key]

通过键直接查找,如果存在就返回对应的值,如果不存在则返回0

	map<char, int>map1;
	map1['a'] = 1;
	map1['b'] = 2;

	cout << map1['a'] << endl; // 返回1
	cout << map1['c'] << endl; // 返回0

2. map.find(key)

返回key对应的迭代器,如果不存在则返回map.end(),时间复杂度为O(logN)

	if (map1.find('d') == map1.end())
		cout << "NOT FONUND" << endl;
	cout << map1.find('a')->second << endl; // 输出1

3. map.count(key)

如果key存在就返回1,如果不存在则返回0。

	cout << "map.count():" << endl;
	cout << map1.count('b') << endl; // 返回1
	cout << map1.count('d') << endl; // 返回0

完整测试代码:

#include<bits/stdc++.h>
using namespace std;

int main() {
	map<char, int>map1;
	map1['a'] = 1;
	map1['b'] = 2;

	cout << map1['a'] << endl; // 返回1
	cout << map1['c'] << endl; // 返回0

	cout << "map.find():" << endl;
	if (map1.find('d') == map1.end())
		cout << "NOT FONUND" << endl;
	cout << map1.find('a')->second << endl; // 输出1

	cout << "map.count():" << endl;
	cout << map1.count('b') << endl; // 返回1
	cout << map1.count('d') << endl; // 返回0

	return 1;
}

在这里插入图片描述

发现一个有趣的问题:

输出一个不存在的key的map映射值时,会把这个值存到map1里面,0为对应的value。
cout<<map[不存在的key];

#include<bits/stdc++.h>
using namespace std;

int main() {
	map<char, int>map1;
	map1['a'] = 1;
	map1['b'] = 2;

	cout << map1['a'] << endl; // 返回1
	cout << map1['c'] << endl; // 这里相当于存入了['c',0]到map1中

	cout << "map.find():" << endl;
	if (map1.find('c') == map1.end())
		cout << "NOT FONUND" << endl;
	cout << map1.find('c')->second << endl; // 返回0

	cout << "map.count():" << endl;
	cout << map1.count('b') << endl; // 返回1
	cout << map1.count('c') << endl; // 'c'存在所以返回1

	return 1;
}

在这里插入图片描述

  • 12
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值