Hi, I'm having a problem with my looping over a vector, and deleting values from another vector sometimes crashes my program. I have this vector of int's to keep track of which elements should be removed.
std::vector<int> trEn;
Then I loop through this vector:
struct enemyStruct {
float x, y, health, mhealth, speed, turnspeed;
double angle, tangle;
};
std::vector<enemyStruct> enemies;
The loop looks like this:
for ( unsigned int i = 0; i < bullets.size(); i++ ) {
for ( unsigned int j = 0; j < enemies.size(); j++ ) {
if ( bullets[i].x > enemies[j].x-10 && bullets[i].x < enemies[j].x+10 && bullets[i].y > enemies[j].y-10 && bullets[i].y < enemies[j].y+10 )
{
enemies[j].health-=bullets[i].dmg;
if(enemies[j].health<=0){trEn.push_back(j);break;}
}
}
}
The bullets vector is just another vector similar to the enemies vector, but with bullets in it. That one does not seem to be the problem. All this code works well, but when it comes to actually delete the items in my enemies vector the program sometimes crashes.
std::reverse( trEn.begin(), trEn.end() );
for ( unsigned int g = 0; g < trEn.size(); g++ ) {
unsigned int atmp = trEn.at(g);
if(atmp<=enemies.size()&&atmp>=0)enemies.erase(enemies.begin()+atmp,enemies.begin()+atmp+1);
} trEn.clear();
First I reverse the vector of int´s so that it will go from back to front. If i did´nt do this all values after trEn[0] would be invalid. This is the loop which gives me a crash, but only sometimes. What I´m trying to do is a top-down shooter game, and it seems that when lots of things should be removed at the same time it just crashes. Please help me with this!
Just ask if I was unclear or if there is anything missing.