Reputation:
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
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
Reputation: 10417
erase
-remove_if
.
bulletEnemyObjects.erase(
std::remove_if(bulletEnemyObjects.begin(), bulletEnemyObjects.end(),
[](Entity *p) { return !p->GetAlive(); }
),
bulletEnemyObjects.end()
);
Upvotes: 1