线程常量错误 C++

thread const error C++

谁能告诉我为什么这段代码会产生错误?

#include <iostream>
#include <map>
#include <vector>
#include <thread>
#include <mutex>
#include <stdexcept>
using namespace std;

void thread_func(const std::map<string, int>& shared) {
    for (int i = 0; i < 10000; ++i) {
        if (shared["what"] != 2 || shared["when"] != 4) {
            throw std::logic_error("not read safe");
        }
    }
}

int main() {
    std::map<string, int> shared;
    shared["what"] = 2;
    shared["when"] = 4;

    vector<thread> threads;
    for (int i = 0; i < 100; ++i) {
        threads.push_back(thread(thread_func, shared));
    }

    for (auto& th : threads) {
        th.join();
    }

    return 0;
}

这会产生以下错误

error: passing ‘const std::map<std::basic_string<char>, int>’ as ‘this’ argument of ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](std::map<_Key, _Tp, _Compare, _Alloc>::key_type&&) [with _Key = std::basic_string<char>; _Tp = int; _Compare = std::less<std::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::basic_string<char>, int> >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = int; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = std::basic_string<char>]’ discards qualifiers [-fpermissive]
         if (shared["what"] != 2 || shared["when"] != 4) {

有人可以用这个指导我正确的方向吗?

谢谢

std::map::operator[] 可以修改映射,因为它插入参数键(如果不存在),因此不能在常量对象上调用。

改用std::map::at()