How to change a set element?

Eric.Q picture Eric.Q · Mar 7, 2012 · Viewed 7.4k times · Source

I want to change the element in a set, so I used set<T>::iterator. However, the compiler argues "the element is const". Then I realized that set<T>::iterator is a const_iterator...

So, how I can change the element? Erase it and then insert a new one?

Answer

Naveen picture Naveen · Mar 7, 2012

The elements of the set will be in sorted order. If you are allowed to modify an element, then this sorting order can not be maintained. Hence you can not modify the item. You need to erase the existing element and insert a new one.