map with const keys but non const values?

后端 未结 5 614
半阙折子戏
半阙折子戏 2021-01-12 18:00

I have a situation, where I would like to have a map that does not allow to add/remove keys after initialization, but the values are allowed to change (thus I cannot simply

5条回答
  •  花落未央
    2021-01-12 18:44

    I usually regard this as a pitfall in C++ more than a feature, but, if it fits your application, you can just use pointer values.

    #include 
    #include 
    
    int main(int argc, char ** argv)
    {
        using namespace std;
        const map> myMap = { {1, make_shared(100)} };
        // *(myMap[1]) = 2;  // Does not compile
        *(myMap.at(1)) = 2;
        for (auto & element : myMap)
        {
            *(element.second) = 0;
        }
        return 0;
    }
    

    Which is really just a simpler version of this other answer (obviously you may choose between shared_ptr / unique_ptr as needed).

提交回复
热议问题