Re: stl::map: return default value without inserting a new element?
la 04/07/2010 12:45 AM James Kanze skribis:
On Apr 6, 8:15 pm, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
I can only offer conjectures. First, storing the default value
is an overhead unnecessary for most applications of
std::map<>. Second, and probably more serious a consequence:
It would be somewhat cumbersome to use the modified map<>
template with value_types that don't support default
construction because, in those cases, you would have to
designate a not_found_value manually.
Most likely, it was simply that they had to choose some
behavior, and since creating a new element is what AWK, perl and
a number of other programs do... It has the disadvantage that
you can't use [] on a const map, in addition to requiring a
default constructor for the object.
That's not true (scalar return how many slots are filled):
$ perl -e 'my %map; $_ = $map{not_there}; print scalar %map, "\n"'
0
However, if you go deeper through an inexistant ref, then it is annoyingly
autovivified:
$ perl -e 'my %map; $_ = $map{not_there}[0]; print scalar %map, "\n"; print
scalar @{$map{not_there}}, "\n"'
1/8
0
Even the array got created and stored there, but despite accessing its 1st
element, its length remains 0 as the 2nd print showed.
regards
Daniel