std::map 上 [] 运算符的声明如下:
T& operator[] ( const key_type& x );
不是这个有原因吗?
T& operator[] ( const key_type& x );
const T& operator[] const ( const key_type& x );
因为当您需要在 const 方法中访问成员映射时,这将非常有用。
从 C++11 开始std::map::at,提供 const 和非常量访问。
相反,如果元素不在地图中operator[],它将引发异常。std::out_of_range
operator[]in a map 返回指定键的值,如果该键不存在,则为该键创建一个新的值初始化元素,因此这是不可能的。
如果operator[]会const过载,则添加该元素将不起作用。
这就回答了这个问题。备择方案:
对于C++03 - 您可以使用迭代器(这些是const与非const耦合的find)。在C++11中,您可以使用该at方法。
这些答案是正确的,因为operator[]如果键不存在,则具有添加键的语义,但我想添加另一个观点:
注意如何operator[]返回一个T&. 也就是说,它返回对与value关联的 的引用key。但是如果里面没有key呢map?我们应该返回什么?没有“空引用”之类的东西,抛出异常会很烦人。
This would be one good reason for no operator[] const. What would you return to the user if you couldn't add anything to the map (because the operator is const), but they are looking for an item that doesn't exist? A good solution to this problem is to not have the operator[] const.
如果 (non- const)operator[]不存在,则创建密钥。
该const运算符的版本(如果存在)必须具有不同的语义,因为它无法添加新键。
我相信您会同意,具有const和const不具有显着不同语义的重载将是一堆蠕虫。因此没有const提供版本。
但是有一个 constfind()成员,因此您可以在代码中使用它。
因为 的语义operator[]是如果它不存在则添加键。