Removing multiple elements from a vector c++ -


here code checks if 2 units killed after attack each other, pass in position in vector when remove 1 vector changed in size , therefore 2nd unit out of range. how can remove both simultaneously?

if ((myhealth <= 0) && (enemyhealth <= 0)) {     playerunits.erase(playerunits.begin() + myunit, playerunits.begin() + enemyunit); } else if (myhealth <= 0) {     playerunits.erase(playerunits.begin() + myunit); } else if (enemyhealth <= 0) {     playerunits.erase(playerunits.begin() + enemyunit); } 

first point: in first block, call erase(x, y) different expect - erases whole range of elements starting @ index x until before index y. example, if have vector [a,b,c,d,e,f,g], erase(2,5) erase indexes 2,3,4, end [a,b,f,g]. i'm guessing want erase 2 elements, not entire range.

second point: dieter lücking pointed out, erase higher index element first, this:

if (myunit > enemyunit) {     playerunits.erase(playerunits.begin() + myunit);     playerunits.erase(playerunits.begin() + enemyunit); } else {     playerunits.erase(playerunits.begin() + enemyunit);     playerunits.erase(playerunits.begin() + myunit); } 

Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

c++ - No viable overloaded operator for references a map -

java - UML - How would you draw a try catch in a sequence diagram? -