You did not say anything about the container you are looking for. The type of container depends on which iterators are invalid. Obviously, the iterator for the element to be erased is invalid, but, for example, in std::vector all iterators that passed the element to be erased will be invalid (including end() ). And for an unknown reason, although set::erase only invalidates the iterator for the element to be erased, it does not return the iterator to the next element.
So std::set :
while (x != abc.end()) // end() will not change and even can be stored { if (...) abc.erase(x++); // increments before erasing else ++x; }
source share