Does the Standard explicitly forbid modifying a container within std::for_each
?
More specifically, in case of std::list
iterators are not invalidated when the list is modified. Thus, the following code works:
std::list<int> list;
list.push_front(5);
list.push_front(10);
auto it = list.end();
it--; // point to 5
std::for_each(list.begin(), list.end(), [&](int i){
/* the line below will remove the last element in the list;
* list will have only one element (the currently processed one);
* list.end() is not invalidated and we exit for_each() */
list.erase(it);
});
This is definitely a bad code. But is it legal?
Does the Standard explicitly forbid modifying a container within
std::for_each
?
The only thing I can think of that would make this code not standard compliant is that in [alg.foreach]
we have
Complexity: Applies
f
exactlylast - first
times.
f
being the function for_each
applies.
Since the list is modified and an element is removed we no longer satisfy that complexity. I do not know if that make it non conforming but it is the only thing I could see that would not allow you to remove elements from the container while using for_each
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