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

2021-12-21 00:00:00 iterator visual-c++ vector c++ erase

我有一个向量,它存储指向许多动态实例化的对象的指针,我试图遍历该向量并删除某些元素(从向量中删除并销毁对象),但是我遇到了麻烦.这是它的样子:

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.

推荐答案

你需要小心,因为 erase() 将使现有的迭代器失效.但是,它将返回一个您可以使用的新的有效迭代器:

You need to be careful because erase() will invalidate existing iterators. However, it will return 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;
   }
}

相关文章