Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const map element access

People also ask

How do you access elements on a map?

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.

What is Const map?

A map is called constant with constant value if for all , i.e., if all elements of are sent to same element of .

Can a std map be const?

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().