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;
}
}
这篇关于如何擦除 &删除指向存储在向量中的对象的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何擦除 &删除指向存储在向量中的对象的指针?


- C++ 协变模板 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01