How to erase amp; delete pointers to objects stored in a vector?(如何擦除 amp;删除指向存储在向量中的对象的指针?)
问题描述
我有一个向量,它存储指向许多动态实例化的对象的指针,我试图遍历该向量并删除某些元素(从向量中删除并销毁对象),但是我遇到了麻烦.这是它的样子:
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;
}
}
这篇关于如何擦除 &删除指向存储在向量中的对象的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何擦除 &删除指向存储在向量中的对象的指针?
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
