Sam Sam - 2 months ago 9
C++ Question

remove_if: Predicate error when passing a function returning bool

I have this pre-defined function.

void attack(std::vector<GameObject*> objects, unsigned damage) {


for (GameObject* object : objects) {
object->takeDamage(damage);
auto isDead = object->isDead();
objects.erase(std::remove_if(objects.begin(),objects.end(),isDead), objects.end());
}
}


This is my isDead function

bool isDead() const {
if (destructed) {
std::cout << "memory error" << std::endl;
}

return life <= 0;
}


This is the error I keep getting. Have tried a lot of things, but not at all able to figure this one out. Any help appreciated!

error: expression cannot be used as a function
{ return bool(_M_pred(*__it)); }

Answer
  1. isDead is a variable in the function. You can't use it as an argument to remove_if.

  2. You can't use a regular member function as argument to std::remove_if either. Use a lambda function instead.

  3. Don't erase objects from a container while you are iterating over it using a range for loop.

  4. Change the argument to attack to be a reference. Otherwise, you will be removing objects from a copy, not the original container.

Here's an updated version of attack:

void attack(std::vector<GameObject*>& objects, unsigned damage)
{
   for (GameObject* object : objects)
   {
      object->takeDamage(damage);
   }

   objects.erase(std::remove_if(objects.begin(),objects.end(), [](GameObject* object){return object->isDead();}), objects.end());
}
Comments