修改std :: for_each中的容器

Kan*_*ane 7 c++ language-lawyer

标准是否明确禁止在其中修改容器std::for_each

更具体地说,在std::list修改列表时,迭代器不会失效.因此,以下代码有效:

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);
});
Run Code Online (Sandbox Code Playgroud)

这绝对是一个糟糕的代码.但这是合法的吗?

Nat*_*ica 3

标准是否明确禁止修改其中的容器std::for_each

我能想到的唯一会让这段代码不符合标准的是[alg.foreach]我们有

复杂性:f恰好适用于last - first时间。

f是该函数for_each适用的。

由于列表被修改并且元素被删除,我们不再满足这种复杂性。我不知道这是否使它不符合要求,但这是我能看到的唯一一件事,它不允许您在使用时从容器中删除元素for_each