remove_if:传递返回bool的函数时谓词错误
remove_if: Predicate error when passing a function returning bool
我有这个预定义的函数。
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));}
-
isDead
为函数中的变量。你不能用它作为remove_if
的参数 -
也不能使用普通成员函数作为
std::remove_if
的参数。使用lambda函数代替。 -
当你使用range for循环遍历容器时,不要从容器中删除对象
-
将参数更改为
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());
相关文章:
- 如何在 STL 函数中找到传递给谓词的元素的索引?
- 尝试使用谓词函数会导致错误:"std::sort"未找到匹配的重载函数
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 如何在算法中使用谓词函数find_if?
- 是否可以使用三元切换/控制/谓词成员函数调用?
- 解释标准库排序函数C++的比较谓词的工作原理?
- 调用非静态函数作为谓词?
- <未解析的重载函数类型>调用二进制谓词
- 在 O(N) 时间内使用布尔谓词函数对向量进行排序
- 为什么指向非静态成员函数的指针不能用作标准库算法的一元谓词
- 条件变量的"wait"函数在提供谓词时导致意外行为
- 具有成员函数的一元谓词
- 创建一个区分值和谓词的模板函数
- 我的谓词函数有什么问题?
- STL中使用的C++自定义比较类型(函数谓词与较少结构)
- 使用谓词模板函数从此处实例化错误
- 在C++类中使用谓词函数指针
- 使用构造函数作为谓词
- 如何将isnan用作std::find_if(c++11)的谓词函数
- 错误C2914:排序函数无法识别要使用重载谓词的哪个版本