[英]C++ Remove object from vector?
我想从播放器 class 内部名为“movelist”的向量中删除 class Attack
的 object。 我尝试使用它并收到此错误:
error: no match for 'operator==' (operand types are 'Attack' and 'const Attack')
有什么建议么?
void Player::del_attack(Attack a1)
{
Attack to_rmv=a1;
movelist.erase(std::remove(movelist.begin(), movelist.end(), to_rmv), movelist.end());
}
我有
#include <algorithm>
#include <vector>
问题是您没有为Attack
class 定义operator==
。 如果您考虑一下,这是必要的。 要从向量中删除等于to_rmv
的元素,算法需要知道如何测试两个Attack
对象是否相等。
最简单的答案是为Attack
定义operator==
,例如:
// return true if x equals y, false otherwise
bool operator==(const Attack& x, const Attack& y)
{
// your code goes here
}
您可能需要将此运算符设为Attack
class 的friend
。
std::remove()
使用operator==
将元素与您要删除的值进行比较。 如果没有为您的 class 定义它,那么您应该会遇到这样的错误。
为Attack
添加这样的重载应该就足够了。 例如,对Attack
使用简单的struct
:
struct Attack {
int attackId;
int strength;
};
bool operator==(Attack const& a, Attack const& b) {
return a.attackId == b.attackId &&
a.strength == b.strength;
}
编译器资源管理器示例: https://godbolt.org/z/8dhrab
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.