operator[] in std::map

F

Fab

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;
}

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
 
I

Ian Collins

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;
}

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.
 
Z

Zhihao Yuan

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top