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

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

Leave a Comment