开发者

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

开发者 https://www.devze.com 2023-03-20 15:16 出处:网络
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)

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开发者_JAVA技巧 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?


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号