user3906336
user3906336

Reputation:

Removing an object from a vector based on a member function from the object

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?

Upvotes: 0

Views: 85

Answers (2)

Neil Kirk
Neil Kirk

Reputation: 21773

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.

Upvotes: 0

ikh
ikh

Reputation: 10417

erase-remove_if.

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

(live example)

Upvotes: 1

Related Questions