本文介绍了在基于范围的for循环中从容器中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从基于范围的for循环中正在使用的容器中删除元素。这会导致未定义的行为吗?或者在 erase()
之后的元素
的下一个值将是下一个元素应该是什么,如果我didn' t erase()
?
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,基于范围的语句等价于:
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循环中从容器中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!