remove_if:传递返回bool的函数时谓词错误

remove_if: Predicate error when passing a function returning bool

本文关键字:函数 谓词 错误 bool 返回 if remove      更新时间:2023-10-16

我有这个预定义的函数。

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());
    }
}

这是我的isDead函数

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

这是我一直得到的错误。我尝试了很多方法,但还是没能解决这个问题。任何帮助,感谢!

错误:表达式不能用作函数{返回bool(_M_pred(*__it));}

  1. isDead为函数中的变量。你不能用它作为remove_if的参数

  2. 也不能使用普通成员函数作为std::remove_if的参数。使用lambda函数代替。

  3. 当你使用range for循环遍历容器时,不要从容器中删除对象

  4. 将参数更改为attack以作为引用。否则,您将从副本中删除对象,而不是从原始容器中删除对象。

这是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());
}

isDead()是你的一个类的成员函数,这就是为什么它不起作用:你没有提供this指针(对象实例)来调用它。对了,remove_if的谓词必须只有一个类型为objects::value_type的参数。

这样做:

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