map 中的坑

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 element

If 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           => 50
d           => 0
mymap.end() => 0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章