[英]c++ STL map.find() or map.operator[] cannot be used in class member function with const qualifier
I'm confused by the following code, why it cannot be successfully compiled? 我对以下代码感到困惑,为什么它无法成功编译?
class Test {
public:
int GetValue( int key ) const
{
return testMap[key];
}
map<const int, const int> testMap;
};
There is always a compling error: 始终存在编译错误:
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).
I've tried to put const qualifier everywhere but it still couldn't pass. 我试图将const限定符放在任何地方,但它仍然无法通过。 Could you tell me why?
你能告诉我为什么吗?
operator[]
is not const
, because it inserts an element if one doesn't already exist with the given key. operator[]
不是const
,因为如果某个元素与给定键不存在,则它会插入一个元素。 find()
does have a const
overload, so you can call it with a const
instance or via a const
reference or pointer. find()
确实有一个const
重载,所以你可以用const
实例或const
引用或指针来调用它。
In C++11, there is std::map::at()
, which adds bounds checking and raises an exception if an element with the given key is not present. 在C ++ 11中,有
std::map::at()
,它添加了边界检查,如果不存在具有给定键的元素,则引发异常。 So you can say 所以你可以说
class Test {
public:
int GetValue( int key ) const
{
return testMap.at(key);
}
std::map<const int, const int> testMap;
};
Otherwise, use find()
: 否则,使用
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
}
}
You got an excellent answer by juanchopanza juanchopanza得到了一个很好的答案
Just wanted to show a boost
way to return something that's not valid 只是想展示一种
boost
方式来返回无效的东西
with boost::optional
you can return empty type 使用
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.