我想从当前在基于范围的 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
}
这篇关于在基于范围的 for 循环内从容器中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
编译器如何处理编译时分支?What do compilers do with compile-time branching?(编译器如何处理编译时分支?)
我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗Can I use if (pointer) instead of if (pointer != NULL)?(我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?)
在 C/C++ 中检查空指针Checking for NULL pointer in C/C++(在 C/C++ 中检查空指针)
比较运算符的数学式链接-如“if((5<j<=1))&quMath-like chaining of the comparison operator - as in, quot;if ( (5lt;jlt;=1) )quot;(比较运算符的数学式链接-如“if((5<j<=1)))
“if constexpr()"之间的区别与“if()"Difference between quot;if constexpr()quot; Vs quot;if()quot;(“if constexpr()之间的区别与“if())
C++,'if' 表达式中的变量声明C++, variable declaration in #39;if#39; expression(C++,if 表达式中的变量声明)