1

Lets suppose I have a unsorted list of iterators to delete defined as

std::vector<std::vector<int>::iterator>  _unsortedIterList;

Of another vector defined as:

std::vector<int> _listValues;

Then this code will not work (since erasing will invalidate the remaining iterators).

for ( auto it: _unsortedIterList)
{
   _listValues.erase(it);
}

Is there a way to erase all of the iterators properly?

1 Answer 1

4

Erasing invalidates iterators at or after the point of erase. So all you have to do is ensure that we erase back to front:

// because random access iterators are comparable
std::sort(_unsortedIterList.begin(), _unsortedIterList.end(),
    std::greater<>{});

// now this is back-to-front, so each erase will keep every other iterator valid
for (auto it : _unsortedIterList) {
    _listValues.erase(it);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.