17

Possible Duplicate:
C++ STL set update is tedious: I can't change an element in place

I have extracted the problem and changed names and so for simplicities sake.

Basically I instantiate a class and I stock it in a std::set, later on I'd like to have a reference to the class so that I can check its values and modify them...

The simplified code:

        MyClass tmpClass;
        std::set<MyClass > setMyClass;
        setMyClass.insert(tmpClass);
        std::set<MyClass >::iterator iter;
        iter=setMyClass.begin();
        MyClass &tmpClass2=*iter;

and the error:

error C2440: 'initializing' : cannot convert from 'const MyClass' to 'MyClass &'

(I removed parts of the error message, "MVB::Run::" to clear it up too.)

if I add a preceding 'const' to the last line of code then everything works well but then I can't change the value...

Is this normal behaviour and I have to, say, remove the data, change values and put it back again?

I have the feeling that this has something to do with the sorting of the set but I won't touch the variables that are used for the sorting.

Community
  • 1
  • 1
Valmond
  • 2,897
  • 8
  • 29
  • 49

2 Answers2

20

I you are certain you won't touch the variables that are used for the sorting the you could work around this by using a const_cast like this:

    MyClass tmpClass;
    std::set<MyClass > setMyClass;
    setMyClass.insert(tmpClass);
    std::set<MyClass >::iterator iter;
    iter=setMyClass.begin();
    const MyClass &tmpClass2=*iter;

    MyClass &tmpClass3 = const_cast<MyClass&>(tmpClass2);

Alternatively, you could declare the members of the class that you intend to change as mutable.

user1055604
  • 1,624
  • 11
  • 28
  • 3
    You can do this, but it's bad practice. – Oliver Charlesworth Mar 15 '12 at 20:54
  • 1
    @Oliver: having const iterators is quite annoying in case you have heterogeneous lookup and you want to change the non key part. I agree that const_cast's are bad practice but what alternatives are there besides a similar bad practice of using mutable all over the place or taking a performance penalty using erase / insert. – gast128 Aug 03 '19 at 12:51
  • You can also use a set of MyClass pointers, which are hashable/sortable independent of its variables. (I.e., You can modify its variables through the pointer) – cid Oct 01 '19 at 21:49
14

Yes, this is expected. If you were able to edit the objects already in the set, the applied sort order might no longer apply, leading to undefined behaviour.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680