0

I am having trouble creating a erase-remove idiom to remove an object from a vector based on the results of a function of that object.

Example, I have an vector here:

std::vector<Entity*> bulletEnemyObjects;

that stores objects of type Entity which each have a variable

bool alive;

that is accessed by a function in the object's class

bool Entity::GetAlive()
{
    return alive;
}

I need to iterate through the vector, and remove any objects that return false to the GetAlive() function. Any help possible here?

1

2 Answers 2

1

erase-remove_if.

bulletEnemyObjects.erase(
    std::remove_if(bulletEnemyObjects.begin(), bulletEnemyObjects.end(),
        [](Entity *p) { return !p->GetAlive(); }
        ),
    bulletEnemyObjects.end()
    );

(live example)

1
  • @FireFreak111 this is called the erase-remove idiom for future reference.
    – Simple
    Aug 11, 2014 at 12:24
0

You will need to make your GetAlive function const.

bulletEnemyObjects.erase(remove_if(bulletEnemyObjects.begin(), bulletEnemyObjects.end(), [](const Entity* entity){ return ! entity->GetAlive(); }), bulletEnemyObjects.end());

Note that this will not delete the entity object pointed to. You may or may not need to do this. It also assumes there are no null pointers.

11
  • Is there no way for the function not to be const? GetAlive is set to false based on events, having it as const defeats the purpose of the variable.
    – user3906336
    Aug 11, 2014 at 10:26
  • No, GetAlive can be non-const. As you see, the type of bulletEnemyObjects is std::vector<Entity*>, not std::vector<const Entity*>
    – ikh
    Aug 11, 2014 at 10:29
  • @FireFreak111 You can remove the const from my code snippet. But GetAlive being const only means that calling this function won't change the object. It doesn't mean the value returned can't change between calls. If it only returns a value, you should make it const.
    – Neil Kirk
    Aug 11, 2014 at 10:31
  • @ikh Can, but shouldn't.
    – Neil Kirk
    Aug 11, 2014 at 10:32
  • @NeilKirk I guessed the real GetAlive of OP's code has some reason for non-const; But after some thought, it seems no >o<
    – ikh
    Aug 11, 2014 at 10:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.