C++ map访问丢弃限定符(const)

cdl*_*ary 106 c++ maps stl const

以下代码表示将map传递constoperator[]方法会丢弃限定符:

#include <iostream>
#include <map>
#include <string>

using namespace std;

class MapWrapper {
public:
    const int &get_value(const int &key) const {
        return _map[key];
    }

private:
    map<int, int> _map;
};

int main() {
    MapWrapper mw;
    cout << mw.get_value(42) << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是因为地图访问中可能出现的分配吗?没有地图访问的函数可以声明为const吗?

MapWrapper.cpp:10: error: passing ‘const std::map<int, int, std::less<int>, std::allocator<std::pair<const int, int> > >’ as ‘this’ argument of ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = int, _Tp = int, _Compare = std::less<int>, _Alloc = std::allocator<std::pair<const int, int> >]’ discards qualifiers

luk*_*uke 145

std::mapoperator []未声明为const,不能因自己的行为:

T&operator [](const键和键)

返回对映射到等效于key的键的值的引用,如果此键尚不存在则执行插入.

因此,无法声明您的函数const,并使用地图operator[].

std::mapfind()功能允许您在不修改地图的情况下查找密钥.

find()返回一个iterator,或const_iterator一个std::pair含有两个键(.first)并将该值(.second).

在C++ 11,你也可以使用at()std::map.如果element不存在,则该函数抛出std::out_of_range异常,与之形成对比operator [].

  • 另外:VALUE = map.find(KEY) - > second; 我必须知道'find()'返回一个迭代器,它是一对类型. (7认同)
  • 我想在C11中添加你可以使用:std :: map :: at(key)并避免使用迭代器. (5认同)
  • 有趣.我认为C++会区分左值'运算符[]`(例如`foo [bar] = baz`)和rvalue`运算符[]`(例如`x = foo [bar]`) - 后者当然可以是const. (2认同)

Ric*_*ard 12

由于operator[]没有const限定的重载,因此无法在const限定的函数中安全地使用它.这可能是因为当前的重载是为了返回和设置键值而建立的.

相反,你可以使用:

VALUE = map.find(KEY)->second;
Run Code Online (Sandbox Code Playgroud)

或者,在C++ 11中,您可以使用at()运算符:

VALUE = map.at(KEY);
Run Code Online (Sandbox Code Playgroud)


小智 11

您不能operator[]在地图上使用const该方法,const因为它允许您修改地图(您可以指定_map[key]).请尝试使用该find方法.


Nat*_*hen 7

一些较新版本的GCC头文件(我机器上的4.1和4.2)具有非标准成员函数map :: at(),如果键不在地图中,则声明为const和throw std :: out_of_range.

const mapped_type& at(const key_type& __k) const
Run Code Online (Sandbox Code Playgroud)

根据函数注释中的引用,似乎已将其建议为标准库中的新成员函数.