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

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

问题描述:

我对 const 有疑问.说我有:

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

由于与映射的 const 冲突,这种代码在编译时会产生错误(如果我注释打印映射值的行,一切都很好),并且如果我在函数原型中全部去掉const"很好.我真的不明白问题出在哪里..

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

有什么帮助吗?

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

myObj.someMap.at(0)

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

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