std::set iterator automatically const [duplicate]

2019-01-18 04:30发布

问题:

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.

回答1:

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.



回答2:

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.



标签: c++ set const std