Is it allowed to erase an element pointed by iterator, and advance the same iterator in one line to go to next element?
set<int>::iterator it = S.begin();
while (it != S.end()) {
if (shouldBeRemoved(*it)) {
S.erase(it++); // is this line valid?
} else {
++it;
}
}
Yes, it is valid.
Rationale:
it++incrementsitso that it refers to the next element but yields a copy of itsoriginal value. Thus,
itdoesn’t refer to the element that is removed whenerase()is called.And in case of
std::setonly iterators to the erased element are invalidated.#1You can consider this code example as a boilerplate code to remove an element to which your iterator is referring.
References:
For
std::set,#1C++03 Standard 23.1.2/8: