使用swap-and-pop迭代时擦除向量中的元素 [英] Erasing element in a vector while iterating using swap-and-pop
本文介绍了使用swap-and-pop迭代时擦除向量中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在迭代向量时删除某些元素,但以下代码导致向量迭代器不可递增"断言失败.
I want to erase certain elements while iterating a vector, but the below code results in a "vector iterator not incrementable" assertion failure.
for(auto iter=vec.begin(); iter!=vec.end(); ++iter)
{
if((*iter).isDead())
{
std::swap(*iter, vec.back());//swap with the back
vec.pop_back(); //erase the element
}
}
这段代码有什么问题?
推荐答案
您正在增加与当前元素交换的元素;如果那是最后一个元素,那么您刚刚删除了它并使您的迭代器无效.如果你没有擦除,你只想增加,使用类似的东西:
You are incrementing past the element you've swapped with the current element; and if that was the last element, then you have just erased it and invalidated your iterator. You only want to increment if you didn't erase, using something like:
for(auto iter=vec.begin(); iter!=vec.end();)
{
if((*iter).isDead())
{
std::swap(*iter, vec.back());//swap with the back
vec.pop_back(); //erase the element
} else {
++iter;
}
}
这篇关于使用swap-and-pop迭代时擦除向量中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文