安全的方式从std :: vector连续擦除? [英] Safe way to continuously erase from a std::vector?
本文介绍了安全的方式从std :: vector连续擦除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我认为下面的代码会工作,但当目标小部件在向量的末尾时崩溃。
I thought the following code would work but it crashes when the target widget is at the end of the vector.
for(std::vector<AguiWidget*>::iterator it = children.begin();
it != children.end(); ++it)
{
if((*it) == widget)
it = children.erase(it);
}
我想让它通过并删除任何实例。我明白这个方法是N ^ 2,但由于这是事件驱动它是罚款。我只是不知道为什么这应该失败。
I want it to go through and delete any instance it finds of widget. I understand this method is N^2 but since this is event driven it is fine. I just don't know why this should fail. When it does, 'it' == widget.
感谢
推荐答案
p>您可以使用erase-remove成语清除等于小部件
的所有元素。
You can use the erase-remove idiom to erase all elements that are equal to widget
.
children.erase(remove(children.begin(), children.end(), widget), children.end());
这篇关于安全的方式从std :: vector连续擦除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文