首页 > 解决方案 > C ++从向量中删除对象?

问题描述

我想Attack从播放器类中名为“movelist”的向量中删除一个类对象。我尝试使用并收到此错误:

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>

标签: c++vector

解决方案


问题是你还没有operator==为你的Attack班级定义。如果您考虑一下,这是必要的。要从向量中删除等于 的元素to_rmv,算法需要知道如何测试两个Attack对象是否相等。

最简单的答案是定义operator==for Attack,例如:

// return true if x equals y, false otherwise
bool operator==(const Attack& x, const Attack& y)
{
    // your code goes here
}

您可能需要将此运算符设为friend您的Attack班级。


推荐阅读