STL中map的使用要点

来源:互联网 发布:正规淘宝刷平台官网 编辑:程序博客网 时间:2024/06/01 15:46

我们都知道, 当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 k2, to do things


      最好对it->second是否为empty进行判断。  作为程序员, 不要依赖于未知假设。