c++ - 修改 std::for_each 中的容器

标签 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);
});

这绝对是一个错误的代码。但这合法吗?

最佳答案

Does the Standard explicitly forbid modifying a container within std::for_each?

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

Complexity: Applies f exactly last - first times.

f 是函数 for_each 适用。

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

时从容器中删除元素的东西

关于c++ - 修改 std::for_each 中的容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35277564/

相关文章:

c++ - 您可以在迭代时从 std::forward_list 中删除元素吗?

c++ - 这个带有空捕获列表的 lambda 如何能够引用到达范围名称?

c - a[a[0]] = 1 会产生未定义的行为吗?

c++ - &a[n] 是否有效,其中 n 是数组的大小?

c++ - 在作为静态成员包含在另一个类中的类的构造函数中使用 cout

c++ - 通过libstdc++调试

c++ - 为什么这个 if 语句没有输出任何东西? (C++)

c++ - vector 的高效组合最小值和平均值计算

c++ - bool的bitwise "and"能保证不短路吗?

c++ - 为多个输入选择选项