C++ const map元素访问

ice*_*ere 88 c++ stl const map

我试图使用operator []访问const C++映射中的元素,但此方法失败.我也尝试用"at()"来做同样的事情.这次工作.但是,我找不到任何关于使用"at()"来访问const C++映射中的元素的引用."at()"是C++地图中新添加的函数吗?我在哪里可以找到更多关于此的信息?非常感谢你!

一个例子如下:

#include <iostream>
#include <map>

using namespace std;

int main()
{
        map<int, char> A;
        A[1] = 'b';
        A[3] = 'c';

        const map<int, char> B = A;

        cout << B.at(3) << endl; // it works
        cout << B[3] << endl;  // it does not work

}
Run Code Online (Sandbox Code Playgroud)

对于使用"B [3]",它在编译期间返回以下错误:

t01.cpp:14:错误:将'const std :: map,std :: allocator >>'传递为'_Tp&std :: map <_Key,_Tp,_Compare,_Alloc> :: operator []的'this'参数( const _Key&)[with _Key = int,_Tp = char,_Compare = std :: less,_Alloc = std :: allocator>]'丢弃限定符

使用的编译器是g ++ 4.2.1

CB *_*ley 111

at()std::mapC++ 11中的一种新方法.

它不是像operator[]没有给定键的元素那样插入新的默认构造元素,而是抛出std::out_of_range异常.(这类似于at()for dequevector.的行为.)

由于这种行为,有一个const重载是有意义的at(),不像那样operator[]总是有可能改变地图.

  • 我只需要评论一下,省略 const 运算符 [] 是没有意义的,它也可能为未映射的元素抛出异常而不是更改映射。 (3认同)

Kon*_*lph 32

如果a中不存在元素map,operator []则会添加它 - 这显然不能在const映射中工作,因此C++不定义const运算符的版本.这是编译器类型检查器防止潜在运行时错误的一个很好的例子.

在你的情况,你需要使用find,而不是将如果存在返回(迭代器)元素,它永远不会改变map.如果某个项不存在,则会向地图返回一个迭代器end().

at不存在,甚至不应该编译.也许这是一个"编译器扩展"(=一个bug 新的C++ 0x).