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

时间:2013-10-16 16:58:10

标签: 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];
}

如何从m中获取值,使其在const函数的上下文中起作用?

1 个答案:

答案 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;
}