Topic: Why ist there no const version of operator[] for map?
Author: odie@hal9000.vc-graz.ac.at (Christoph Rabel)
Date: Thu, 21 Aug 2003 05:18:25 +0000 (UTC) Raw View
Hi!
I wonder where there is no const counterpart to the existing version.
I recently stumbled on that problem when writing a getValue(Key)
Function that I declared as const. I couldnt use operator[] to get the
value but had to use find().
Is there any harm in adding this function?
thx for any insights,
Christoph
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Author: jdennett@acm.org (James Dennett)
Date: Thu, 21 Aug 2003 09:31:01 +0000 (UTC) Raw View
Christoph Rabel wrote:
> Hi!
>
> I wonder where there is no const counterpart to the existing version.
> I recently stumbled on that problem when writing a getValue(Key)
> Function that I declared as const. I couldnt use operator[] to get the
> value but had to use find().
>
> Is there any harm in adding this function?
>
> thx for any insights,
This has been covered a number of times in the past;
a search of the archives through Google Groups might
well dig up repeated discussions.
In a nutshell:
(a) There is none because the convenience of having
operator[] automatically add values if they are absent
was chosen
(b) It is unacceptable to many for a const version to
behave differently than a non-const version, except in
const-ness, so a const operator[] cannot be added.
You can write a function to get an element from a map,
but you'll need to decide what it should do if the element
is absent. You'll just have to choose a name for the
function: the name operator[] has already been taken for
a function with different semantics.
-- James.
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]