'Why doesn't std::set<K, C, A>::erase take a const_iterator?

It appears that according to ISO 14882 2003 (aka the Holy Standard of C++) std::set<K, C, A>::erase takes iterator as a parameter (not a const_iterator)

from 23.3.3 [2]

void erase(iterator position);

It might also be noteworthy that on my implementation of STL which came with VS2008, erase takes a const_iterator which led to an unpleasant surprise when I tried to compile my code with another compiler. Now, since my version takes a const_iterator, then it is possible to implement erase with a const_iterator(as if it wasn't self-evident).

I suppose the standards committee had some implementation in mind (or an existing implementation at hand) which would require erase to take an iterator.

  • If you agree that this is the case, can you please describe an implementation of set::erase which would require to modify the element that was going to be removed (I can't).
  • If you disagree, please tell me why on Earth would they come up with this decision? I mean, erasing an element is just some rearranging of pointers!

It just occurred to me that even in case of iterator you can't modify the element in a set. But the question still holds: why not const_iterator, especially if they're equivalent in some sense?



Solution 1:[1]

This was a defect. Since C++11, set<K,C,A>::erase takes a const_iterator:

iterator erase(const_iterator position);

This paper from 2007 illustrated that error and showed implementations to avoid it. I am not sure if this paper is the reason for the change in the standard, but it's probably a good guess.

Solution 2:[2]

Can't really think of any reason for it to need an iterator, so I'm leaning toward the arbitrary: any op that modifies the structure would take an iterator to let the user know that what previously worked with the iterator might not afterward:

  • erase invalidates the iterator.
  • insert(iter, val) changes the next value.
  • etc.

Solution 3:[3]

My only guess is because insert, upper_bound, lower_bound and find are returning iterator (not const iterator). I don't see other explanation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lightness Races in Orbit
Solution 2
Solution 3 BЈовић