C++,通过常量引用访问 std::map 元素 [英] C++, accessing std::map element via const reference
本文介绍了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.
}
这篇关于C++,通过常量引用访问 std::map 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文