Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, accessing std::map element via const reference

Tags:

c++

stl

stdmap

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?

like image 820
volatile Avatar asked Dec 20 '12 18:12

volatile


1 Answers

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.
}
like image 96
juanchopanza Avatar answered Nov 11 '22 10:11

juanchopanza