在基于范围的 for 循环内从容器中删除元素

2021-12-11 00:00:00 for-loop c++ c++11

我想从当前在基于范围的 for 循环中使用的容器中删除一个元素.这会导致未定义的行为吗?或者,如果我没有调用 erase()erase() 之后 element 的下一个值会是下一个元素应该是什么?

I want to erase an element from a container which is being currently used within a ranged-based for loop. Will this cause undefined behaviour? Or will the next value of element after erase() be what the next element is supposed to be if I didn't call erase()?

示例:

std::map<int, int> someMap;
/* Fill in someMap */
for (auto& element : someMap)
{
    /* ... */
    if ( /* Some condition */ )
        someMap.erase(element.first);
}

推荐答案

这应该是一个未定义的行为.因为根据 14882/2011,基于范围的 for 语句等效于:

It should be a undefined behavior. Because according to 14882/2011 the range-based for statement is equivalent to:

auto && __range = range-init;
for ( auto __begin = begin-expr(__range),
   __end = end-expr(__range);
   __begin != __end;
   ++__begin ) {
   for-range-declaration = *__begin;
   statement
}

相关文章