简体   繁体   English

C++ 从向量中删除 object?

[英]C++ Remove object from vector?

I would like to remove an object of class Attack from vector called "movelist" that is inside the player class.我想从播放器 class 内部名为“movelist”的向量中删除 class Attack的 object。 I tried to use this and got this error:我尝试使用并收到此错误:

error: no match for 'operator==' (operand types are 'Attack' and 'const Attack')

Any suggestions?有什么建议么?

void Player::del_attack(Attack a1)
{
   Attack to_rmv=a1;
   movelist.erase(std::remove(movelist.begin(), movelist.end(), to_rmv), movelist.end());
}

I've got我有

#include <algorithm>
#include <vector>

The problem is that you haven't defined operator== for your Attack class.问题是您没有为Attack class 定义operator== If you think about it, this is necessary.如果您考虑一下,这是必要的。 To remove an element from your vector that is equal to to_rmv , the algorithm needs to know how to test if two Attack objects are equal.要从向量中删除等于to_rmv的元素,算法需要知道如何测试两个Attack对象是否相等。

The simplest answer is to define operator== for Attack , eg:最简单的答案是为Attack定义operator== ,例如:

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

You might need to make this operator a friend of your Attack class.您可能需要将此运算符设为Attack class 的friend

std::remove() uses operator== to compare the elements against the value you are wanting to remove. std::remove()使用operator==将元素与您要删除的值进行比较。 If it is not defined for your class, then you should expect such an error.如果没有为您的 class 定义它,那么您应该会遇到这样的错误。

Adding such an overload to Attack ought to suffice.Attack添加这样的重载应该就足够了。 For example, using a simple struct for an 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; 
}

Example on Compiler Explorer: https://godbolt.org/z/8dhrab编译器资源管理器示例: https://godbolt.org/z/8dhrab

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM