我有這樣的代碼(這是一個復制錯誤的小版本的代碼),它給出了某種錯誤的記憶體。它洗掉了物件,所以只剩下了nullptr。我不知道為什么,但它不想從串列中洗掉指標。
#include <iostream>
#include <list>
// casual include
在這里我創建了一個類,它是我所有其他類的基礎
。class Object // a virtual class
{
public:
bool needs_delete = false;
virtual void tick(){}。
virtual void render() {}。
};
一個繼承自我之前創建的Object類的播放器類
class Player : public Object
{
public:
float x, y; // <--只看代碼,不讀dis。
Player(float x, float y) : //i initialize the "x" & "y" with the x & y the user has set in the constructor。
x(x),y(y)。
{}
void tick() override //只是看一下代碼。
{
x ;
if (x > 10000)
{
needs_delete = true;
}
}
void render() override //只是看一下代碼。
{
//沒什么......。
}
};
只是主函式。在這一點上,我只是在寫文本,因為stackoverflow不讓我發布這塊持續的抑郁癥。
int main()
{
std::list<Object*>* myObjs = new std::list<Object*>; //a list that will contain the objects.
for (int i = 0; i < 1000; i ) //我創建1k player只是為了測驗。
{
myObjs->push_back(new Player(i, 0) )。)
}
while (true)
{
if (myObjs->size() == 0) //如果沒有物件,我就跳出回圈。
break。
for (Object* obj : *myObjs) //更新物件。
{
obj->tick()。
obj->render()。
//其他一些東西。
}
//DA PART I HAVE NO IDEA HOW TO DO[/span
// pls help cuz i suck
for (Object* obj : *myObjs) // help pls :)
{
//baisicly here i want to delete the object and remove it from the list
if (obj-> needs_delete)
{
std::cout << "洗掉物件
"。
delete obj;
myObjs->remove(obj)。
}
}
}
}
uj5u.com熱心網友回復:
怎么樣:
myObjs->remove_if[](auto& pObj)
{
if ( pObj-> needs_delete )
{
delete pObj;
return true;
}
else; }
return false;
});
uj5u.com熱心網友回復:
你可以使用一個std::vector,用for回圈遍歷你的物件,并在另一個std::vector中存盤需要洗掉的物件的索引,然后洗掉它們。它應該是這樣的:
std::vector<GameObject*> objects;
std::vector<int> deleteIndex;
for (int i = 0; i < objects.size(); i ) {
if (object[i]->delete) deleteIndex.push_back(i)。
}
for(auto index : deleteIndex){
delete objects[i];
objects.erase(objects.begin() i) 。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/332987.html
標籤:
