I want std::set to have mutable elements. But std::set provides only const elements. Is there a way to work the problem around?
Why I need mutable set? Let me explain.
I have a class:
struct Cow
{
Cow(const std::string &name)
: name(name)
, age (0)
{}
void Moo()
{ std::cout << name << "is mooing." << std::endl; }
const std::string name;
int age ;
};
I want to store elements of this class in std::set. Elements are identified by their name (it is always const). But I also want mutable access to non-const methods and members.
I can store them in std::map instead. But I don't want to store name separately from the object (the name is part of the object).
I can duplicate name. One name is stored as a key in std::map and another is stored inside the object. But it's memory inefficient, also it might cause data inconsistency when the key has one name and the object has another name.
So what can I do?
You can use
mutablekeyword to work around the problem.The output: