Heya all, long time no see. Anyhow, I've got a situation where a vector of sprites* is checked against another vector of sprites*. If the pair being checked intersect, I'd like to delete them both. I can handle single-delete passes, but can't wrap my head around double-deletes, since the outer loop's iterator would also need to be incremented, but only if the inner iterator was incremented... anyhow, it's kicking my butt in practice.
In the mean time, I simply set the sprite's lifetime to zero, so on the next loop, a different iteration catches and deletes the sprite.
Code:
for ( auto target = EnemyBullets.begin(); target != EnemyBullets.end(); ++target ) {
for ( auto shot = Bullets.begin(); shot != Bullets.end(); ++shot ) {
if (( *target )->getGlobalBounds().intersects(( *shot )->getGlobalBounds())) {
( *target )->setLifeTime( 0 );
( *shot )->setLifeTime( 0 );
}
}
}
The above works, but optimally first, I'd like to delete the two sprites directly. All my attempts segfault so far. Something like:
Code:
for (auto shot = Bullets.begin(); shot != Bullets.end(); ++shot) {
for (auto target = EnemyBullets.begin(); target != EnemyBullets.end();) {
if((*shot)->getGlobalBounds().intersects((*target)->getGlobalBounds())) {
delete *shot;
delete *target;
shot = Bullets.erase(shot);
target = EnemyBullets.erase(target);
} else {
++target;
}
}
}
If I figure it out, I'll post an update.