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