慎用mmap[key]!!!

#include <cstdio>
#include <cstring>
#include <map>
using namespace std;
#include <iostream>

int main() {
	map<string, int> mmap;
	cout << "Before test: ";
	for (map<string, int>::iterator it = mmap.begin();
			it != mmap.end(); ++it) cout << it->first << " ";
	cout << endl << endl;
	
	cout << "test:" << endl;
	if (mmap["ZhengDongjian"] == 0) {
		cout << "string \"ZhengDongjian\" doesn't exist." << endl << endl;
	}
	cout << "Insert ZhengDongjian: ";
	pair<map<string, int>::iterator, bool> res = mmap.insert(make_pair("ZhengDongjian", 1));
	if (res.second) cout << "Insert success!" << endl;
	else cout << "Insert failed!" << endl << endl;

	cout << "After that: ";
	for (map<string, int>::iterator it = mmap.begin();
			it != mmap.end(); ++it) cout << it->first << " ";
	cout << endl << "Test over..." << endl;

	return 0;
}

可以看出,如果使用operator[](const string& _str).根据返回结果是否为0来判断该元素是否存在于map中是不靠谱的,因为这会导致该元素(键)被直接插入,而这可能是你绝对不想做的!所以,不要自觉没有问题就用它(⊙o⊙)哦.

在判断元素是否存在map中应适用count函数:

if (mmap.count("ZhengDongjian") != 0) {
    cout << "string already exist!" << endl;
} else {
    cout << "string doesn't exist!" << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值