【发布时间】:2011-07-05 07:28:59
【问题描述】:
我尝试使用operator[] 访问const map 中的元素,但是这个方法失败了。我也尝试使用at() 来做同样的事情。这次奏效了。但是,我找不到任何关于使用at() 访问const map 中的元素的参考资料。 at()是map中新增的功能吗?我在哪里可以找到有关此的更多信息?非常感谢!
一个例子如下:
#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
}
使用“B[3]”,编译时返回如下错误:
t01.cpp:14: 错误: 传递‘const std::map
> >' 作为'_Tp& 的'this' 参数 std::map<_key _tp _compare _alloc>::operator[](const _Key&) [with _Key = int, _Tp = char, _Compare = std::less, _Alloc = std::allocator<:pair int char> >]' 丢弃限定符
使用的编译器是g++ 4.2.1
【问题讨论】:
标签: c++ dictionary stl constants