C++ STL – Accessing std::map Element via const Reference

c++stdmapstl

I have a proble with const. say I have :

class A{
    friend std::ostream& operator<<(std::ostream& os,const A& myObj);

   private:
    std::map<int,int> someMap;
    int someInteger;
 };
 std::ostream& operator<<(std::ostream& os,const A& myObj){
  os<<myObj.someInteger<<std::endl;
  os<<myObj.someMap[0]<<std::endl;
  }

This kind of code generates an error at compilation due to a const conflict with the map (if I comment the line printing the map value all is fine), and if I get rid of the 'const' in the function prototype all is fine. I really do not see where is the problem..

Any help please?

Best Answer

std::map::operator[] is not const, because it inserts an element if one does not already exist. In c++11, you can use std::map::at() instead:

myObj.someMap.at(0)

Otherwise, you can check whether the element exists first using std::map::find,

if (myObj.find(0) != myObj.end())
{
  // element with key 0 exists in map
} else 
{
  // do something else.
}
Related Question