C++ map at() function is used to access the elements in the map with the given key value. It throws an exception out_of _range, if the accessed key is not present in the map.
A map is called constant with constant value if for all , i.e., if all elements of are sent to same element of .
This comes as quite a surprise to me, but the STL map doesn't have a const index operator. That is, B[3] cannot be read-only. From the manual: Since operator[] might insert a new element into the map, it can't possibly be a const member function.
at()
is a new method for std::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 a std::out_of_range
exception. (This is similar to the behaviour of at()
for deque
and vector
.)
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.
If an element doesn’t exist in a map
, the operator []
will add it – which obviously cannot work in a const
map so C++ does not define a const
version of the operator. This is a nice example of the compiler’s type checker preventing a potential runtime error.
In your case, you need to use find
instead which will only return an (iterator to the) element if it exists, it will never modify the map
. If an item doesn’t exist, it returns an iterator to the map’s end()
.
at
doesn’t exist and shouldn’t even compile. Perhaps this is a “compiler extension” (= a bug new in C++0x).
The []-operator will create a new entry in the map if the given key does not exists. It may thus change the map.
See this link.
This comes as quite a surprise to me, but the STL map doesn't have a const
index operator. That is, B[3]
cannot be read-only. From the manual:
Since operator[] might insert a new element into the map, it can't possibly be a const member function.
I have no idea about at()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With