List of bullets c++

906 views Asked by At

I'm writing the Contra Game by Directx9 and c++ please help me about list of bullets

i'm trying below code but it's error: vector intertor incompatible

 std::vector<Bullet*> bullets
if (mKeyboard->IsKeyPress(DIK_X))
{
    Bullet* toShoot = new Bullet(noneType, _position.x, _position.y, RIGHT);
    toShoot->Init();
    bullets.push_back(toShoot);
}

Update Funtion:

 std::vector<Bullet*>::iterator it = bullets.begin();


 while ((it) != bullets.end())
  {
    (*it)->Update(gameTime, c);

    if ((*it)->IsLive() == false)
    {
        bullets.erase(it++);
    }
  }

Render funtion

std::vector<Bullet*>::iterator it = bullets.begin();
while (it != bullets.end())
{
    if ((*it)->IsLive())
    {
        (*it++)->Render(gr, cx, cy);
    }
}
2

There are 2 answers

0
Marcelo Cantos On

You can't just increment an iterator passed to erase(…). Do this instead:

if (!(*it)->IsLive()) {
  it = bullets.erase(it);
} else {
  ++it;
}

Your Render function has a different bug. It gets stuck on the first non-live bullet, since the increment is inside the if-block. This is one reason for(…) is usually preferable to while(…):

for (auto it = bullets.begin(); it != bullets.end(); ++it) {
    if (…) {
        …
    }
}

In fact, the Update function should be likewise changed, but omit the ++it.

0
PaulMcKenzie On

In your Update function, you are calling the erase while iterating over a vector. The problem is that your it iterator can get invalidated if it is being used in the loop at the same time you're erasing from the vector.

The alternative is to use the erase/remove_if idiom:

#include <algorithm>
//...
bullets.erase(std::remove_if(bullets.begin(), bullets.end(), 
              [&](Bullet& b) { b.Update(gameTime, c); return !b.IsLive(); }),
              bullets.end());

The algorithm function remove_if() is called to determine which bullets will be removed by the erase() function. Note that the lambda includes the logic you used to determine if a bullet should be removed.