[英]c++ STL map.find() or map.operator[] cannot be used in class member function with const qualifier
我对以下代码感到困惑,为什么它无法成功编译?
class Test {
public:
int GetValue( int key ) const
{
return testMap[key];
}
map<const int, const int> testMap;
};
始终存在编译错误:
error C2678: binary '[': no operator found which takes "const std :: map <_Kty,_Ty>" type of the left operand operator (or there is no acceptable conversion).
我试图将const限定符放在任何地方,但它仍然无法通过。 你能告诉我为什么吗?
operator[]
不是const
,因为如果某个元素与给定键不存在,则它会插入一个元素。 find()
确实有一个const
重载,所以你可以用const
实例或const
引用或指针来调用它。
在C ++ 11中,有std::map::at()
,它添加了边界检查,如果不存在具有给定键的元素,则引发异常。 所以你可以说
class Test {
public:
int GetValue( int key ) const
{
return testMap.at(key);
}
std::map<const int, const int> testMap;
};
否则,使用find()
:
int GetValue( int key ) const
{
auto it = testMap.find(key);
if (it != testMap.end()) {
return it->second;
} else {
// key not found, do something about it
}
}
juanchopanza得到了一个很好的答案
只是想展示一种boost
方式来返回无效的东西
使用boost::optional
您可以返回空类型
#include<boost\optional.hpp>
...
boost::optional<int> GetValue(int key){
auto it = testMap.find(key);
if (it != testMap.end()) {
return it->second;
} else {
return boost::optional<int>();
}
}
boost::optional<int> val = GetValue(your_key);
if(!val) //Not empty
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.