4

In the following loop I'm using a pre-calculated end iterator:

std::list::iterator end = MyList.end(); for (std::list::iterator it = MyList.begin(); it != end ;) it = MyList.erase(it); 

When erasing an element in a std::list, can the MyList.end() change its value so that end != MyList.end() anymore?

2
  • Rather than try to edit the accepted answer to be more comprehensive, I edited the question so it's just about std::list. One should read each container's documentation for the specifics of what invalidation guarantees it does or does not offer. Commented Nov 20, 2018 at 7:52
  • 1
    In general, don't save end() , it only works for some containers, so don't get into the habit. Commented Nov 20, 2018 at 8:16

1 Answer 1

5

No.

n3376 23.3.5.4

iterator erase(const_iterator position); iterator erase(const_iterator first, const_iterator last); 

Effects: Invalidates only the iterators and references to the erased elements.

Sign up to request clarification or add additional context in comments.

2 Comments

Just for completeness, keep in mind that this applies to std::list and some other container types but isn't true for all container types (such as std::vector).
@ForEveR search set/map erase :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.