Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > operator[] in std::map

Reply
Thread Tools

operator[] in std::map

 
 
Fab
Guest
Posts: n/a
 
      11-11-2012
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
 
Reply With Quote
 
 
 
 
Ian Collins
Guest
Posts: n/a
 
      11-11-2012
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
 
Reply With Quote
 
 
 
 
Zhihao Yuan
Guest
Posts: n/a
 
      11-13-2012
> > 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.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off




Advertisments