标准是否明确禁止修改 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
exactlylast - first
times.
f
是函数 for_each
适用。
由于列表被修改并删除了一个元素,我们不再满足这种复杂性。我不知道这是否会使它不符合要求,但这是我唯一能看到的不允许您在使用 for_each
关于c++ - 修改 std::for_each 中的容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35277564/