I need to remove an element from a std::list
after finding it with std::find
. What is the behavior of calling std::list::erase
with the end()
of the list? My case is something like this:
std::list<T> mylist;
T value;
std::list::iterator it = std::find(mylist.begin(), mylist.end(), value);
std::list::iterator next = mylist.erase(it);
cplusplus.com says:
If position (or the range) is valid, the function never throws exceptions (no-throw guarantee). Otherwise, it causes undefined behavior.
but what I don't know is whether end()
is considered valid there.
That site uses the vague (and arguably incorrect) term "valid", but the library specification (C++11 23.2.3) uses the more specific term "dereferenceable" - meaning that the iterator must refer to an object. The past-the-end iterator is not dereferenceable, so erasing it gives undefined behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With