Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

operator[] in std::map

78 views
Skip to first unread message

Fab

unread,
Nov 11, 2012, 4:20:15 PM11/11/12
to
Dear all

I use std::map for some application. I would like to return a const
reference to some value with the operator[] function. I have a public
method of the following form:

const value& getValue( const int i ) const
{
return myMap[i];
}

where myMap is of type std::map. When I compile this with gcc, I get an
error due to the const method qualifier. I can't figure out why? When
I do the return statement like:

return myMap.find( i )->second;

then everything works. I find the first method more elegant, but like I
said, why is this not working?

Thanks + regards
Fab

Ian Collins

unread,
Nov 11, 2012, 4:23:12 PM11/11/12
to
On 11/12/12 10:20, Fab wrote:
> Dear all
>
> I use std::map for some application. I would like to return a const
> reference to some value with the operator[] function. I have a public
> method of the following form:
>
> const value& getValue( const int i ) const
> {
> return myMap[i];
> }
>
> where myMap is of type std::map. When I compile this with gcc, I get an
> error due to the const method qualifier. I can't figure out why?

Map's operator[] isn't const. It will modify the map (by inserting a
default value) if the element does not exist.

--
Ian Collins

bartek szurgot

unread,
Nov 12, 2012, 12:00:31 PM11/12/12
to Ian Collins
indeed. there is one more drawback - operator[] requires that "value" is
default constructable (because of reasons described above).

--
pozdrawiam serdecznie / best regards,
bartek szurgot
/* http://www.baszerr.eu */

Zhihao Yuan

unread,
Nov 13, 2012, 6:22:23 PM11/13/12
to Ian Collins
> > Map's operator[] isn't const. It will modify the map (by inserting a
>
> > default value) if the element does not exist.
>
>
>
>
>
> indeed. there is one more drawback - operator[] requires that "value" is
>
> default constructable (because of reasons described above).
>

And for the same reason, you should use insert() to add new values; no temporary is needed.
0 new messages