如何清除&删除指向存储在向量中的对象的指针? [英] How to erase & delete pointers to objects stored in a vector?

查看:122
本文介绍了如何清除&删除指向存储在向量中的对象的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
   }
}

这篇关于如何清除&amp;删除指向存储在向量中的对象的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆