operator[] and std::map

Gawain Bolton boltong@nortelnetworks.com
Fri Mar 21 13:24:00 GMT 2003


Gilbert Laycock wrote:

> Should it be possible to use operator[] from std::map in a const
> context?
>
> For example, in class A, the isFive method will not compile (g++
> 3.2.3) because _m[c] does not preserve const. In contrast std::vector
> provides a const version of operator[].

No, there cannot be a const version of operator[] for std::map since, if
the key passed is not already present in the map, it will be added with
an associated value constructed using value_type's default constructor.

What you must do is use "find()" and, if the key is present in the map,
check the associated value.


Gawain

--
-------------------------------------------------------------------------------
Gawain Bolton                     | E-mail: boltong@nortelnetworks.com
UMTS Development                  |
Nortel Networks                   | Voice:  ESN 579-3763   +33 1.39.44.37.63
Guyancourt, France                | FAX:    ESN 579-3009   +33 1.39.44.30.09
-------------------------------------------------------------------------------





More information about the Libstdc++ mailing list