Search code examples
c++stliteratorlanguage-lawyerc++20

Are there any iterator invalidation rules for <algorithms> operations?


For example, in C++20 vector we have erase and erase_if. Their effects are defined in terms of remove and remove_if respectively (for erase [vector.erasure/1]):

Effects: Equivalent to:

auto it = remove(c.begin(), c.end(), value);

auto r = distance(it, c.end());

c.erase(it, c.end());

return r;

The relevant clause is (probably) [container.reqmts/67] (parentheses mine)

Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container.

But I can't find anything specified about iterators for any operation in <algorithms>, including remove/remove_if.


Solution

  • Algorithms can't invalidate iterators, because they have no power to resize containers. All they can do is assign values to other objects. (That's why remove and remove_if leave the job only half-done.)

    Some algorithms can "invalidate" objects in the sense of leaving them in a moved-from state, or in an unspecified state, but those aren't "invalidated" in container terms. The storage, and the objects, are still where they were before. Only the values have changed.