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?
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 .
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.
By default, a Map in C++ is sorted in increasing order based on its key.
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
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