为什么std :: map没有const访问器? [英] Why does std::map not have a const accessor?

查看:130
本文介绍了为什么std :: map没有const访问器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆