Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying a container within std::for_each

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?

like image 332
Kane Avatar asked Feb 08 '16 19:02

Kane


1 Answers

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 exactly last - 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

like image 153
NathanOliver Avatar answered Oct 03 '22 19:10

NathanOliver