1,auto value = map.at(“test”); 如果map中没有这个key会报错。
2,auto value = map[“test”]; 没有不会报错,且会插入一个新的pair,value为空。
源码如下:
T& operator[](const key_type& k)
{
return (*((insert(value_type(k, T()))).first)).second;
}
3,用map自己提供的find函数即可,完全没有副作用。如下map_find:
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
string map_find(const map<string,string> &map,const string &key)
{
auto it = map.find(key);
if(it != map.end())
return it->second;
return "";
// return map.find(key)!=map.end() ? map.find(key)->second : "";
}
int main()
{
map<string,string> map{std::make_pair("111","test"),std::make_pair("222","test2"),std::make_pair("333","test3"),};
cout <<"Before:"<<endl;
for_each(map.begin(),map.end(),[](auto &pa){cout<<"first:"<<pa.first<<",second:"<<pa.second<<endl;});
cout <<"After:"<<endl;
//auto value = map.at("test");//err
auto value = map["test"];//自动添加一个pair元素
auto value2 = map_find(map,"test");
if(value2.empty())
cout<<"empty..."<<endl;//这里的empty有两个含义:要么是没有这个key存在;要么存在,但是value是空。
else
cout<<value2<<endl;
for_each(map.begin(),map.end(),[](auto &pa){cout<<"first:"<<pa.first<<",second:"<<pa.second<<endl;});
return 0;
}