C++,通过const引用访问std :: map元素

vol*_*ile 5 c++ stl stdmap

const有问题.说我有:

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;
  }
Run Code Online (Sandbox Code Playgroud)

由于与地图的const冲突,这种代码在编译时会产生错误(如果我注释打印地图值的行一切都很好),如果我摆脱了函数原型中的'const',一切都很好.我真的没有看到问题在哪里..

有什么帮助吗?

jua*_*nza 25

std::map::operator[]不是const,因为它插入一个元素(如果尚不存在).在c ++ 11中,您可以使用std::map::at():

myObj.someMap.at(0)
Run Code Online (Sandbox Code Playgroud)

否则,您可以先检查元素是否存在std::map::find,

if (myObj.find(0) != myObj.end())
{
  // element with key 0 exists in map
} else 
{
  // do something else.
}
Run Code Online (Sandbox Code Playgroud)