从标记为 const 的函数中的 std::map 中检索项目



请考虑以下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函数的上下文中工作?

最好的

选择是使用 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;
}

最新更新