STL map关于查找的坑——尽量不使用方括号[ ]查找

(今天在做sdu程序设计思维作业时,遇到了一个坑,记录一下)

map内置函数find,当查找不成功时,返回值为end(),例如

if(mp.find(13)!=mp.end())
   cout<<"Found"<<endl;

还有一种查找方法,即使用方括号[ ]直接查找,例如

if(mp[13])
   cout<<"Found"<<endl;

但是有一点需要注意,如果使用方括号[ ]来直接查找的话,比如mp[13],如果没有查找到13,进而会将13插入到map容器中!

观察以下两个样例

样例一

#include<iostream>
#include<map>
#include<string>
using namespace std;
int main()
{
	map<string, bool> book;
	book["sdu"] = true;
	book["csp"] = true;
	for (map<string, bool>::iterator it = book.begin(); it != book.end(); it++)
		cout << it->first << " ";
}

执行结果为
在这里插入图片描述
样例二

#include<iostream>
#include<map>
#include<string>
using namespace std;
int main()
{
	map<string, bool> book;
	book["sdu"] = true;
	book["csp"] = true;
	if (book["ccf"])
		cout << "yes" << endl;
	for (map<string, bool>::iterator it = book.begin(); it != book.end(); it++)
		cout << it->first << " ";
}

可能想当然认为执行结果为sud csp,但是实际结果却是
在这里插入图片描述
由此可见,尽量不要使用方括号[ ]直接查找

ps:如果map中的值是int\bool类型时,若使用方括号[ ]查找不成功时将其插入后的值默认为0。

例如我们将样例二改为

	for (map<string, bool>::iterator it = book.begin(); it != book.end(); it++)
		if(it->second!=0)
			cout << it->first << " ";

就可以得到理想的输出结果:sdu csp

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值