C ++ const map元素访问 [英] C++ const map element access
问题描述
我试图使用operator []访问const C ++映射中的元素,但此方法失败。我也试图使用at()做同样的事情。这次工作。但是,我找不到任何参考使用at()访问元素在const C ++映射。是at()一个新添加的函数在C ++映射?在哪里可以找到更多的信息?非常感谢!
I tried to use the operator[] access the element in a const C++ map, but this method failed. I also tried to use "at()" to do the same thing. It worked this time. However, I could not find any reference about using "at()" to access element in a const C++ map. Is "at()" a newly added function in C++ map? Where can I find more info about this? Thank you very much!
例如:
#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
}
],它在编译期间返回以下错误:
For using "B[3]", it returned the following errors during compiling:
t01.cpp:14:error:passing'const
std: :map,
std :: allocator>>'as'this''参数'_Tp&
std :: map< _Key,_Tp,_Compare,
_Alloc> :: operator [](const _Key&)[with _Key = int,_Tp = char,_Compare = std :: less,_Alloc =
std :: allocator>]'丢弃限定符
t01.cpp:14: error: passing ‘const std::map, std::allocator > >’ as ‘this’ argument of ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = int, _Tp = char, _Compare = std::less, _Alloc = std::allocator >]’ discards qualifiers
使用的编译器是g ++ 4.2.1
The compiler used is g++ 4.2.1
推荐答案
at()
是C ++ 11中 std :: map
的一种新方法。
而不是插入一个新的默认构造的元素 operator []
如果一个元素与给定的键不存在,它抛出一个 std :: out_of_range
异常。 (这类似于 at()
for deque
和向量
。)
Rather than insert a new default constructed element as operator[]
does if an element with the given key does not exist, it throws a std::out_of_range
exception. (This is similar to the behaviour of at()
for deque
and vector
.)
由于这种行为,有一个 const
code> $ <$ p $ c> $
Because of this behaviour it makes sense for there to be a const
overload of at()
, unlike operator[]
which always has the potential to change the map.
这篇关于C ++ const map元素访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!