How to change a set element?

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?


Solution 1:

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.

Solution 2:

Set elements are constant and may not be modified in place. Modification could change the ordering predicate without changing the position of the element which would violate the constraints of the data structure.

However now in the future (C++17), modifying the element without erasure is possible with the extract member function:

std::set<std::string> stringset{"a", "b", "c"};
auto node = stringset.extract(stringset.begin());
std::string& str = node.value();
str = "d";
stringset.insert(std::move(node));

There is still the cost of list operations but the object itself is not destroyed or copied.