如何清除&删除指向存储在向量中的对象的指针?

如何清除&删除指向存储在向量中的对象的指针?

问题描述:

我有一个向量存储指针动态实例化的许多对象的指针,我试图迭代通过向量和删除某些元素(从向量和销毁对象删除),但我有麻烦。这是它的外观:

I have a vector that stores pointers to many objects instantiated dynamically, and I'm trying to iterate through the vector and remove certain elements (remove from vector and destroy object), but I'm having trouble. Here's what it looks like:

    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时,程序崩溃时出现断言错误。 。
任何人都知道我做错了什么?

When any of the Entity objects get to xPos>1.5, the program crashes with an assertion error... Anyone know what I'm doing wrong?

我使用VC ++ 2008。

I'm using VC++ 2008.

您需要小心,因为 擦除() 会使现有的迭代器无效。但是,ir返回一个新的有效的迭代器你可以使用:

You need to be careful because erase() will invalidate existing iterators. However, ir returns a new valid iterator you can use:

for ( it = Entities.begin(); it != Entities.end(); )
   if( (*it)->getXPos() > 1.5f )
      delete * it;  
      it = Entities.erase(it);
   }
   else {
      ++it;
   }
}