Checking collision of bullets and Asteroids

I'm trying to detect collision between two list of bullets and asteroids. The code works fine, but when the bullet intersects with an asteroid, and that bullet passes through another asteroid, the code gives an assertion, and it says about it can't increment the iterator. I'm sure there is a small bug in that code, but I can't find it.

for (list<Bullet>::iterator itr_bullet = ship.m_Bullets.begin();
itr_bullet!=ship.m_Bullets.end();)
{
for (list<Asteroid>::iterator itr_astroid = asteroids.begin();
itr_astroid!=asteroids.end();
itr_astroid++)
{
if(checkCollision(itr_bullet->getCenter(),itr_astroid->getCenter(),
{
itr_astroid = asteroids.erase(itr_astroid);
}
}
itr_bullet++;
}

• There are lots of collision detection questions on the site. Did you really not find what you were looking for with those? – MichaelHouse Sep 1 '12 at 1:35
• I did, but it seems I have a problem with iterating through the list and erasing an item from it – Ahmed Saleh Sep 1 '12 at 1:36

The problem is that you're removing an asteroid from the list, and then incrementing the iterator without first checking whether you're already at the end of the list.

The usual approach, when iterating over a container, is to remove the 'increment' step from the for clause, and instead to either do the erase (which implicitly does a safe increment), or else increment inside the code inside the for loop:

for (list<Asteroid>::iterator itr_astroid = asteroids.begin(); itr_astroid!=asteroids.end();)
{