Re: Overhead of subscript operator for STL maps
Stephen Horne wrote:
I realise that scripting languages do it, but they get to handle the
[] differently depending on whether its on the left side of an
assignment or not. They still complain if you try to read a
non-existent key.
Actually in many languages (such as for example PHP) relational maps
work exactly that way. That is, you add an element to the map by
"indexing" it with the key and assigning the element. This is a very
common idiom eg. in PHP.
And even with the [] on the left of an assignment, I still think it's
a bit bad, since to me the obvious intent is to overwrite the data for
an existing key.
It might be "obvious" to you because you are used to think like that.
However, in many languages (such as PHP) it's obvious that you are
building a relational map by indexing it. That is, when you say:
myMap[key] = value;
when you are doing is adding 'value' at the "position" 'key' of the map.
Or if there was already such a key, you are replacing its data with the
new value.
std::map has that exact same idea (although it's not as flexible as
PHP because the type of the key and the value are fixed). As exemplified
by Erik, this can be quite handy in some cases, for example because you
can write things like:
words[word]++;
One single command adds a new 'word' to the map and increments its value.
If you want to check if a key exists in the map, that's what the
find() member function is for.