hi guys
ok so i have a vector called health and it has 10 elements, each element is equal to 100.
the way the program works is if the user type 'd' it will reduce health by 10, and if the health is less than 50 all the element in the vector get erased.
But the problem is i dont know how to erase the element. i used v.erase but that didnt work correctly.
The reason it's erasing multiple elements is because you have it in a loop. What's actually happening is this:
vector: [0123456789] <- the 10 elements in your vector
i=0. erase index 0: [123456789]
loop, so i=1, erase index 1: [13456789]
loop, so i=2, erase index 2: [1356789]
i=3, erase index 3: [135789]
i=4, erase index 4: [13579]
i=5, which is >= vector size (which is now 5), so loop ends
leaving you with 5 elements in the array.
Effectively, you're removing all of the even indexes with that loop.
std::vector<int> health(10, tower_health); // construct 10 elements with the value of tower_health
while(health.size()<10)health.push_back(tower_health);
vector::erase() invalidates previous iterators and returns a new iterator pointing to the next element,
1 2 3 4 5 6 7 8 9 10 11 12 13
for (auto it = health.begin(); it != health.end();)
{
*it -= 10;
if (*it < 50)
{
it = health.erase(it);
}
else
{
it++;
}
}
std::remove_if() moves removed elements to the back and returns an iterator to the new end,
1 2 3 4 5 6 7
auto end = std::remove_if(health.begin(), health.end(), [](int& hp) -> bool
{
hp -= 10;
return hp < 50;
});
health.erase(end, health.end());