Answer the question
In order to leave comments, you need to log in
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;
}
const int value
map
std::map
std::map
Answer the question
In order to leave comments, you need to log in
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;
}
But they would make a variable private and a constant method to return a value, and there would be no problems at all.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question