I have the following code, but when I run it, I intermittently get a Debug Assertion Failed error, with the reason "vector iterator not dereferencable".
What I'm trying to do with the program is create a bunch of 2D shapes (squares and circles), then move them about one by one, checking for collisions as they go. When two shapes collide, I want them to be removed, until there is (at most) one shape remaining. About 1 in 3 attempts results in a successful outcome, where the program finds four collisions, then stops. Other times, it will find 1-3 collisions and then error.
I should also mention that I'm relatively new to C++ (and yes, this is a coursework assignment), so if there are any other rookie mistakes in my code, please do point them out!
My methods for moving and colliding seem fine on their own, so I've not included them here.
Square * s1 = new Square(seedCoord(limit), seedCoord(limit), 2.0);
... //There is 9 new shapes created here (squares and circles)
std::vector<Shape*> shape;
shape.push_back(s1);
... //All 9 shapes added to the vector
int m = shape.size();
bool collision = false;
while(m>1) //Keep running until only one shape hasn't collided
{
for (auto i=shape.begin(); i!=(shape.end());) //Perform move on each shape in sequence
{
collision = false; //Set collision boolean to false
(*i)->move(seedCoord(0.5), direction[(rand() % 4)], limit); //Perform move on shape
for (auto j=shape.begin(); j!=(shape.end()-1);) //Check for collision with each shape in sequence
{
if((*i) != (*j)) //Ignore self when checking for collision
{
if((*i)->collide(*j)) //Check for collision
{
std::cout << "Collision between " << (*i) << " and " << (*j) << "\n";
m=m-2; //Lower shapes count by two (ie remove two collided shapes)
delete *i; //Delete pointer to initial shape
i = shape.erase(i); //Erase shape object
delete *j; //Delete pointer to collided shape
j = shape.erase(j); //Erase shape object
collision = true; //Set collision boolean to true
break; //Break out of internal for-loop (shape has been deleted so no more checks are necessary)
}
else
{
j++; //If no collision, move onto next shape
}
}
else
{
j++; //If i=j, move onto next shape
}
}
if(!collision) //If no collision with any shape, move onto next shape
{
i++; //If no collision with any shape, move onto next shape
}
else
{
break; //If collision has occurred, break out of external for-loop (shape has been deleted so no more checks are necessary)
}
}
}