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

Sun*_*day 3 c++ const stdmap

考虑以下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];
}
Run Code Online (Sandbox Code Playgroud)

如何从函数m上下文中获取值const

jua*_*nza 7

您最好的选择是使用该at()方法,const如果找不到该键,该方法将抛出异常.

int A::getValue(int key) const 
{
  return m.at(key);
}
Run Code Online (Sandbox Code Playgroud)

否则,在未找到密钥的情况下,您必须决定返回什么.如果有值,您可以在这些情况下返回,那么您可以使用std::map::find:

int A::getValue(int key) const 
{
  auto it = m.find(key);
  return (it != m.end()) ? it->second : TheNotFoundValue;
}
Run Code Online (Sandbox Code Playgroud)