我有一个 vector ,它存储指向许多动态实例化的对象的指针,我试图遍历 vector 并删除某些元素(从 vector 中删除并销毁对象),但我遇到了麻烦。这是它的样子:
vector<Entity*> Entities;
/* Fill vector here */
vector<Entity*>::iterator it;
for(it=Entities.begin(); it!=Entities.end(); it++)
if((*it)->getXPos() > 1.5f)
Entities.erase(it);
当任何实体对象达到 xPos>1.5 时,程序会因断言错误而崩溃... 有谁知道我做错了什么?
我正在使用 VC++ 2008。
最佳答案
您需要小心,因为 erase()
将使现有的迭代器无效。但是,它将返回一个您可以使用的新的有效迭代器:
for ( it = Entities.begin(); it != Entities.end(); ) {
if( (*it)->getXPos() > 1.5f ) {
delete * it;
it = Entities.erase(it);
}
else {
++it;
}
}
关于c++ - 如何删除和删除指向存储在 vector 中的对象的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/991335/