Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::set iterator automatically const [duplicate]

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.

like image 433
Valmond Avatar asked Mar 15 '12 19:03

Valmond


2 Answers

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.

like image 75
user1055604 Avatar answered Nov 01 '22 06:11

user1055604


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.

like image 31
Oliver Charlesworth Avatar answered Nov 01 '22 06:11

Oliver Charlesworth