其他分享
首页 > 其他分享> > c – 从标记为const的函数中的std :: map中检索项目

c – 从标记为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;
}

标签:c,const,stdmap
来源: https://codeday.me/bug/20190728/1565264.html