E
E
Eugene-1232021-10-27 11:40:05
C++ / C#
Eugene-123, 2021-10-27 11:40:05

How to add an object with constant fields to `std::map`?

Let's say I have the following code:

#include <string>
#include <map>

struct A {
    const int value;
    A(int value) : value{value} {}
};

int main() {
    A a{3};
    std::map<std::string, A> myMap;
    myMap["Hello"] = a; // Error: Copy assignment operator of 'A' is implicitly deleted 
                        // because field 'value' is of const-qualified type 'const int'.
    return 0;
}

In this case, I can't overload `operator=`

I need the following behavior.
1. The field is always constant. No tricks to change it. 2. std::map must contain values. 3. If the key is missing, then a key-value pair must be created in . 4. If the key exists, then replace the value. 5. No default constructors, in the absence of a key. Accessing a dictionary using a key that doesn't exist should throw an exception or stop or something. In general, as I understand it, you need to create a wrapper over ? It would be desirable to achieve such behavior by standard means . What can you suggest? const int value
map

std::mapstd::map

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Eugene-123, 2021-10-27
@Eugene-123

I found a solution here that suits me:

int main() {
    A a{3};
    std::map<std::string, A> myMap;
    const char* key = "Hello";
    const auto it = myMap.find(key);
    if (it != myMap.end())
        myMap.erase(it);
    myMap.emplace(key, a.value);
    return 0;
}

M
maaGames, 2021-10-27
@maaGames

But they would make a variable private and a constant method to return a value, and there would be no problems at all.

W
Wataru, 2021-10-27
@wataru

Store pointers to your type in std::map. Better smart ones, like shared_ptr.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question