我们都知道, 当map不存在某key时, 如果用下标操作, 便会产生新key。 因此, 要特别注意
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
map<string, string> m;
m["k1"] = "good";
if(m["k3"] == "")
{
cout << "no k3" << endl;
// do things
}
else
{
cout << "has k3" << endl;
// do things
}
if(m.find("k3") == m.end())
{
cout << "no k3, to do things" << endl;
// do things
}
else
{
cout << "has k3, to do things" << endl;
// do things
}
return 0;
}
先说说结果:
no k3
has k3, to do things
最好对it->second是否为empty进行判断。 作为程序员, 不要依赖于未知假设。