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

前提是你 提交于 2019-12-10 14:47:00

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/13978170/c-accessing-stdmap-element-via-const-reference

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!