Search code examples
c++crashiteratorerase

C++ vector iterator: erase() last item crash


The following code checks if a ball overlaps with a brick. The brick is highlighted and erased from the list if the overlap occurs.

I am experiencing a core dump when erasing only the last item in the vector brickWall. Commenting the erase() line, the code seems to work well.
After looking through similar issues on forums, I believed I was iterating through and erasing the items in the vector properly, but I suspect it may not be the case.

Any suggestions on this code would be much appreciated!

void Game::updateEntities()
{
    ballMother.update();
    for (std::vector<gdf::Entity>::iterator it = brickWall.begin(); it != brickWall.end(); ++it) 
    {
        if (it->getRect().intersects(ballMother.getRect())) {
            it->rect.setFillColor(sf::Color::Red);
            it = brickWall.erase(it);
        }
        else {
            it->rect.setFillColor(it->colour);                
        }
    }
}

Solution

  • The usual idiom is

    for (std::vector<gdf::Entity>::iterator it = brickWall.begin(); it != brickWall.end(); /*note nothing here*/) 
    {
        if (it->getRect().intersects(ballMother.getRect())) {
            it->rect.setFillColor(sf::Color::Red);
            it = brickWall.erase(it);
        }
        else {
            it->rect.setFillColor(it->colour);                
            ++it;
        }
    }
    

    otherwise you will be skipping elements, as well as eventually crash by going past the end.