简体   繁体   中英

Erasing an element from a vector within a for loop - C++

I'm trying to erase an enemies' health value when they are destroyed and I get the error "No instance of overloaded function "..." matches the argument list if I have the following:

upgradeHealth.erase(inner)

It seems to only accept something like this:

upgradeHealth.erase(upgradeHealth.begin())

I need the element at position inner to be erased so that it matches the enemy that just got destroyed. Here's the for loop:

for (outer = 0; outer < bullets.size(); outer++)              
{
    for (inner = 0; inner < upgrades.size(); inner++)       
    {
        if (upgrades[inner]->HitTest(bullets[outer])) 
        {
            upgradeHealth[inner] -= 1;
            bullets.erase(outer--);
            multiplier += 0.01;
            hasHit = true;
            multiplierTime = 0;
            cout << upgradeHealth[inner] << endl;
            if (upgradeHealth[inner] == 0) 
                upgradeHealth.erase(inner), upgrades.erase(inner), score += 100 * multiplier;
            break;
        }
    }
}

There are only two overloaded member functions erase in class std::vector

iterator erase(iterator position);
iterator erase(iterator first, iterator last);

You can only erase an iterator using the erase(...) methods of the std::vector .

You can check this answer for how to get an iterator from an index. Although I would suggest you rethink your algorithm so that you don't need such a conversion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM