我试图使用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 …