Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::map not have a const accessor?

Tags:

c++

std

c++11

The declaration for the [] operator on a std::map is this:

T& operator[] ( const key_type& x ); 

Is there a reason it isn't this?

T& operator[] ( const key_type& x ); const T& operator[] const ( const key_type& x ); 

Because that would be incredibly useful any time you need to access a member map in a const method.

like image 895
Calder Avatar asked Dec 16 '12 15:12

Calder


2 Answers

As of C++11 there is std::map::at which offers const and non-const access.

In contrast to operator[] it will throw an std::out_of_range exception if the element is not in the map.

like image 165
Stephan Dollberg Avatar answered Sep 23 '22 03:09

Stephan Dollberg


operator[] in a map returns the value at the specified key or creates a new value-initialized element for that key if it's not already present, so it would be impossible.

If operator[] would have a const overload, adding the element wouldn't work.

That answers the question. Alternatives:

For C++03 - you can use iterators (these are const and non-const coupled with find). In C++11 you can use the at method.

like image 43
Luchian Grigore Avatar answered Sep 24 '22 03:09

Luchian Grigore