Why do only non-constant maps provide associative array-like direct element retrieval?
The standard C++ Library: A Tutorial and Reference by Nicolai M. Jossuttis
It's my go-to book when I'm going to use some STL mechanisms in any significant manner. Anyway, I was quickly rereading the chapters on std::map and related algorithms and I noticed a sentence I hadn't thought about before:
Non-constant maps provide a subscript operator for direct element access. However, the index of the subscript operator is not the integral position of the element. ... etc.
Why can only non-constant maps be used in an associative array like manner? It seems that it would be fairly simple to provide read-only semantics in this case. I suppose exceptions would be possible if you tried to retrieve an element with a key that didn't exist (sine you can't add a new key/value to the map if its constant).
I'd like to understand the reasoning behind this if anyone can shed some light :) thanks!
Why can only non-constant maps be used in an associative array like manner?
Because those operators return a reference to the object that is associated with a particular key. If the container does not already contain such an object, operator inserts the default object. Now, if container is constant, you cannot insert any objects into it, and you cannot return a reference to non-existing objects, that's why these operators are available for non-constant containers only.
Throwing an exception in that case is possible, of course, but is not the best way to approach a pretty general cases when object for a given key doesn't exist. Basically, exceptions are extremely expensive and are for exceptional situations, and the above one is not, so it is not worth it.
The better way would be to return an iterator, but then user would have to check if it is not "end", which will make the use case similar to calling find (), so useless. Returning iterators or pointers for constant-only containers is also possible, but that breaks semantics a bit and is confusing.