Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the [] operator const for STL maps?

Tags:

c++

constants

Contrived example, for the sake of the question:

void MyClass::MyFunction( int x ) const {   std::cout << m_map[x] << std::endl } 

This won't compile, since the [] operator is non-const.

This is unfortunate, since the [] syntax looks very clean. Instead, I have to do something like this:

void MyClass::MyFunction( int x ) const {   MyMap iter = m_map.find(x);   std::cout << iter->second << std::endl } 

This has always bugged me. Why is the [] operator non-const?

like image 921
Runcible Avatar asked Sep 25 '09 00:09

Runcible


People also ask

Can a Map be const?

However, you can't type Map as const , which means you can never have a constant Map that disallows set and delete and also knows whether the result of get is undefined or not, rather than always making it return the type x | undefined .

Are std::map sorted?

std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare . Search, removal, and insertion operations have logarithmic complexity.

Are maps sorted in c++?

By default, a Map in C++ is sorted in increasing order based on its key.


1 Answers

For std::map and std::unordered_map, operator[] will insert the index value into the container if it didn't previously exist. It's a little unintuitive, but that's the way it is.

Since it must be allowed to fail and insert a default value, the operator can't be used on a const instance of the container.

http://en.cppreference.com/w/cpp/container/map/operator_at

like image 97
Alan Avatar answered Sep 28 '22 01:09

Alan