为什么std :: map没有const访问器? [英] Why does std::map not have a const accessor?
问题描述
std :: map上的[]运算符的声明如下:
The declaration for the [] operator on a std::map is this:
T& operator[] ( const key_type& x );
有理由不是这样吗?
T& operator[] ( const key_type& x );
const T& operator[] const ( const key_type& x );
因为这将是非常有用的任何时候你需要访问一个成员映射在const方法。 / p>
Because that would be incredibly useful any time you need to access a member map in a const method.
推荐答案
operator []
或为该键创建一个新的价值初始化元素(如果该键尚未存在)。因此这是不可能的。
operator[]
in a map returns the value at the specified key or creates a new value-initialized element for that key if it's not already present, so it would be impossible.
如果 operator []
会有 const
重载,添加元素将不起作用。
If operator[]
would have a const
overload, adding the element wouldn't work.
这回答了问题。替代方法:
That answers the question. Alternatives:
对于 C ++ 03 ,您可以使用迭代器(这些 const
和非 - const
加上 find
)。在 C ++ 11 中,您可以使用方法。
For C++03 - you can use iterators (these are const
and non-const
coupled with find
). In C++11 you can use the at
method.
这篇关于为什么std :: map没有const访问器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!