Search code examples
c++cinder

List iterator not incrementable when checking collision between objects


I am currently coding a space shooter with cinder to learn c++. I am checking collisions between the lasers and the enemys.

void ParticleController::CheckCollisions()
{

  for(std::list<Enemy>::iterator e = enemys_.begin(); e != enemys_.end();)
  {
      for(std::list<LaserParticle>::iterator p = laserParticles_.begin(); p != laserParticles_.end();)
      {
          if(e->GetBoundingBox().intersects(p->GetBoundingBox()))
          {
              e = enemys_.erase(e);
              p = laserParticles_.erase(p);
          }

          else
            ++p;
      }   

      ++e;
  }
}

But I get the error "list iterator not incrementable". I had this error before, but I cant seem to fix it this time.


Solution

  • Very likely it happens when you just have erased the last enemy. In that case erase returns end() and e cannot be incremented anymore.

    if (e != enemys_.end())
      ++e;