Re: need for operator[] in map
On Feb 8, 2:59 pm, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
James Kanze wrote:
On Feb 7, 3:56 pm, "subramanian10...@yahoo.com, India"
[...]
Convenience. It's a bit awkward, in that the semantics which
would be most convenient vary according to what you're using the
map for, and in practice, I rarely use []. (But then, most of
my maps are const, so I can't.) The real question is, of
course, if [] doesn't find the element, what does it do?
Well, the language does not really give you a chance here.
A chance for what? There are really three different reasonable
semantics for a "get" function on an associative container:
1. return a pointer to the value, returning a null pointer if
the value isn't found;
2. throw an exception if the value isn't present, or
3. create a new entry, with a default value (in which case, the
"get" function can't be const---in the other two cases, you
would probably overload the function on const).
The interface of std::map basically implements the first, with
the "getter" called find(), not get (or operator[]), except that
it returns an iterator, rather than a pointer (and the iterator
is to the attribute value pair, not the value). The second
option isn't directly available, and operator[] implements the
third.
I suspect that the reason behind this is that it is easier to
simulate the others when you have the first, rather than vice
versa---with the second, you need a wrapper with a try block to
simulate the others, and with the third, you need some way of
testing whether an element is present to simulate the other two.
I suspect that the operator[] was added mainly to support the
perl/AWK idiom. If you want perl/AWK like associative arrays,
you use it (and you pretty much ignore const). Otherwise, you
use find() and insert().
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34