0

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) extracting 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);
    };
}
quaz0
  • 1
  • 3
  • See [this question](https://stackoverflow.com/questions/52285161/using-mutable-to-allow-modification-of-object-in-unordered-set) for one way to do this. – 1201ProgramAlarm Nov 20 '21 at 21:44
  • @1201ProgramAlarm I've checked and `mutable` doesn't seem to work if you class' member is private (or I'm missing smth, and I need to somehow also modify the setter). – quaz0 Nov 21 '21 at 13:13

1 Answers1

0

After reading this: Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?, I've found the solution. You just need to declare your setter const:

void setVal(string val) const

Although, I still don't understand why declaring your setter non-constant produces a compilation error.

quaz0
  • 1
  • 3
  • 1
    _I still don't understand why declaring your setter non-constant produces a compilation error_ because you can't call a non-const member function on a const object, and the values (keys) stored in an unordered_set are const (to prevent making a change that would change the sort order). – 1201ProgramAlarm Nov 21 '21 at 21:05