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

95 views Asked by At

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.

2

There are 2 answers

0
Sneftel On BEST ANSWER

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.

0
463035818_is_not_an_ai On

An iterator alone cannot invalidate itself or other iterators, you need a reference to the container. That's why the part you quote speaks only of functions that get the container passed.