#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;
}