访问成员unordered_map中的数据时,C++const方法在结构中编译错误

C++ const method compile error in struct when accessing data in member unordered_map

本文关键字:方法 C++const 结构 错误 编译 数据 unordered 成员 map 访问      更新时间:2023-10-16

我不明白我遇到的编译错误。下面是我的用例的一个简化示例。

#include <unordered_map>
#include <iostream>
#using namespace std;
struct C{
    unordered_map<int, string> m;
    C(){
        m[1] = "one";
        m[2] = "two";
    }
    int method() const{
        const string s = m[2];
        return 42;
    }
};
int main() {
    C c;
    cout << c.method() << endl;
    return 0;
}

以下是我的用例要求:

  • 我希望方法method()const,因为我确信它不会更改任何成员字段
  • 由于频繁的数据访问,成员字段m应该是unordered_map(或任何哈希表)

以上代码无法使用error: passing ‘const std::unordered_map<int, std::__cxx11::basic_string<char> >’ as ‘this’ argument discards qualifiers [-fpermissive]进行编译。但是,如果我从方法method()中删除const(我不想或不能这样做),代码编译得很好。我有什么不明白的?在我的用例中,是否没有办法使方法const

顺便说一句,我在Ubuntu 15.10上使用GCC 5.2.1和CLion 1.2.4。

std::unordered_map::operator[]

不是const方法,因为它在不存在元素的情况下插入元素。所以你不能在常数m上使用它。使用

std::unordered_map::at

相反。