Search code examples
c++vectorerase

Remove element from vector using 'this' keyword


Fairly simple question.

I have a Bullet object where at one point when the bullet collides with an object, it gets destroyed and removed from a vector of Bullets.

Each Bullet object has a reference to the vector/list of bullets.

How do I remove it using the this keyword inside the Bullet class when this happens?

void collide(){
    //error C2678: binary '==': no operator found which takes a left-hand operand of type 'Bullet'
    //(or there is no acceptable conversion)
    bullets->erase(std::remove(bullets->begin(), bullets->end(), *this), bullets->end());
}

So yeah that code gives me a strange error. I need to know how to do it without iterating over the vector of bullets using a while/for loop and just using vector functions. Obviously the current method isn't working as it's spewing out the error as commented in the code.

I also tried using find() instead of remove(), same error.


Solution

  • you need to implement the == operator in the bullet class. if you want to delete an item according to it's memory address , you can simple iterate over the vector and find the element naively :

        for (Bullet& bullet : bullets){
            if (&bullet == this){
              bullets.erase(bullet);
                break;
             }
         }