安全的方式从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());