Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   operator[] in std::map (http://www.velocityreviews.com/forums/t954418-operator-in-std-map.html)

Fab 11-11-2012 09:20 PM

operator[] in std::map
 
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 11-11-2012 09:23 PM

Re: operator[] in std::map
 
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

Zhihao Yuan 11-13-2012 11:22 PM

Re: operator[] in std::map
 
> > 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.


All times are GMT. The time now is 07:33 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.