I've a simple custom class, declared as follows, and I've implemented the hasher and comparator functors. The hashing functor uses the standard hash for strings, and the comparator simply checks if the keys are equal, so I'll skip their definitions here.
And I've implemented an unordered_set
containing objects of this class (yes, I know about the unordered_map
, but let's just assume here, that I want to stick specifically to unordered_set
). Later, at some point in time, I'd like to modify the value (but not the key) of the object found through an iterator.
Now, I'm a bit stuck, and my question is:
is there another way to accomplish this except for (1) casting away the constness via const_cast
, which I'd like to avoid, and (2) extract
ing the object from my unordered set, modifying its value and then moving it back and (3) erasing the element and inserting it back after modifying the value?
I've seen similar questions on SO, but the discourse there is always on structs with publicly accessible values.
Code:
class myClass {
private:
string key;
string val;
public:
void getKey();
void getVal();
void setKey(string key);
void setVal(string val);
myClass(string key);
myClass(string key, string val);
}
<...>
<hasher's definition>
<comparator's definition
int main() {
unordered_set<myClass, myClassHasher, myClassComparator> myClassUset;
<...>
string some_val;
auto it = myClassUset.find(myClass{some_key});
if (it != myClassUset.end()) {
it->setVal(some_val);
};
}