我尝试使用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
}
对于使用“B [3]”,它在编译过程中返回以下错误:
使用的编译器是g++ 4.2.1
最佳答案
at()
是C++ 11中std::map
的新方法。
如果具有给定键的元素不存在,则不会像operator[]
那样插入新的默认构造元素,而是引发std::out_of_range
异常。 (这类似于at()
和deque
的vector
的行为。)
由于这种行为,所以const
的at()
重载是有意义的,而operator[]
总是有可能更改 map 。