Вопрос

Is it possible to remove an object from std::list using .remove and the object as a pointer?

Im getting quite confused with pointers. I have the following class for example:

class AsteroidGen{
    public:
        std::list<Asteroid*> listAsteroids;
        void AsteroidGen::generateAsteroid(int amount, int delet);
        void AsteroidGen::DrawAsteroids();
};

That has a list of pointers to my asteroid object. Since it is a pointer I assume I would be able to go through it using pointers and delete it.

In my main class I create an instance of AsteroidGen and populate the list and draw it. This all works fine. I then try to remove one of the items from the list that my bullet has collided with:

bool CheckBulletCollision(Lazer lazer, AsteroidGen asteroids){
    bool collision = false;
    for each(Asteroid *c in asteroids.listAsteroids){
        Position pos = c->pos;
        float lazx = lazer.mPos.x;
        float lazy = lazer.mPos.y;
        float lazz = lazer.mPos.z;
        float distance = sqrt(pow(pos.x - lazx, 2) + pow(pos.y - lazy, 2) + pow(pos.z - lazz, 2));
        if( distance < 2.05){
            asteroids.listAsteroids.remove(c);
            lazergone = true;
            break;
        }
    }
    return collision;
}

i tried going line by line through my code to see what is going wrong, but the list item is not actually removed in the next frame. I am probably not using pointers correctly, I still find them difficult.

Could someone give me advice please! Tell me if I need to add more code, I assumed this would be sufficient Thank you.

Это было полезно?

Решение

You're passing AsteroidGen into the function by value. This means a copy of it is made and the function works on the local copy, which is discarded when the function ends. The asteroid is indeed removed from the list, but from the list stored in the copy.

If you want to modify the AsteroidGen object in the function, you must pass it by reference:

bool CheckBulletCollision(Lazer lazer, AsteroidGen &asteroids) {
  // ... rest of code as before
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top