map 中的坑

来源:互联网 发布:unity3d粒子特效教程 编辑:程序博客网 时间:2024/06/08 12:20

map 中的坑

const map 无法使用map::operator[]

比如下面的代码在编译时会报错一大长串错误(ps: STL库报错就是这么长),仔细阅读,其实就是说const map

string getMapValue(const map<string,string> & mStr2Map,const string key){    return mStr2Map[key];}
error: passing ‘const std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >’ as ‘this’ argument of ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Tp = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Compare = std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, _Alloc = std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >]’ discards qualifiers

请看map::operator[]的说明,即当x存在时,直接返回x对应的值;当x不存在时,会在map中添加key=x,即修改了map,也就是不符合const要求。

T& operator[] ( const key_type& x );Access elementIf x matches the key of an element in the container, the function returns a reference to its mapped value.If x does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the map size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).A call to this function is equivalent to:(*((this->insert(make_pair(x,T()))).first)).second

推荐用法

string getMapValue(const map<string,string> & mStr2Map,const string key){    if(mStr2Map.find(key) != mStr2Map.end())    {        return mStr2Map.find(key)->second;    }    // 抛异常或直接返回空字符串    return "";}

map::find(key)->second 中 key不存在时不报错

map::find(key)->second 当key不存在时,返回map::end()->second, 并不报错,map::end()->second是随机值。

// map::find#include <iostream>#include <map>using namespace std;int main (){    map<char,int> mymap;    mymap['a']=50;    mymap['b']=100;    mymap['c']=150;    // print content:    cout << "elements in mymap:" << endl;    cout << "a           => " << mymap.find('a')->second << endl;    cout << "d           => " << mymap.find('d')->second << endl;    cout << "mymap.end() => " << mymap.end()->second << endl;    return 0;}

输出结果:

elements in mymap:a           => 50d           => 0mymap.end() => 0
1 0