I tried to use the operator[]
access the element in a const 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 map
. Is at()
a newly added function in map
? Where can I find more info about this? Thank you very much!
An example could be the following:
#include <iostream>
#include <map>
int main()
{
std::map<int, char> A;
A[1] = 'b';
A[3] = 'c';
const std::map<int, char> B = A;
std::cout << B.at(3) << std::endl; // it works
std::cout << B[3] << std::endl; // it does not work
}
For using B[3]
, it returned the following errors during compiling:
t01.cpp:14: error: passing ‘const
std::map<int, char, std::less,
std::allocator<std::pair<const int,
char> > >’ 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<std::pair<const int,
char> >]’ discards qualifiers
The compiler used is g++ 4.2.1
Best Answer
at()
is a new method forstd::map
in C++11.Rather than insert a new default constructed element as
operator[]
does if an element with the given key does not exist, it throws astd::out_of_range
exception. (This is similar to the behaviour ofat()
fordeque
andvector
.)Because of this behaviour it makes sense for there to be a
const
overload ofat()
, unlikeoperator[]
which always has the potential to change the map.