考虑以下C ++代码:
// A.h
class A {
private:
std::map<int, int> m;
int getValue(int key) const;
};
// A.cpp
int A::getValue(int key) const {
// build error:
// No viable overloaded operator[] for type 'const std::map<int, int>'
return m[key];
}
如何从m
中获取值,使其在const
函数的上下文中起作用?
答案 0 :(得分:7)
您最好的选择是使用at()
方法const
,如果找不到密钥,则会抛出异常。
int A::getValue(int key) const
{
return m.at(key);
}
否则,在未找到密钥的情况下,您必须决定返回什么。如果在这些情况下您可以返回值,则可以使用std::map::find
:
int A::getValue(int key) const
{
auto it = m.find(key);
return (it != m.end()) ? it->second : TheNotFoundValue;
}