简体   繁体   中英

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. 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. 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.

The simplest answer is to define operator== for Attack , eg:

// 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.

std::remove() uses operator== to compare the elements against the value you are wanting to remove. If it is not defined for your class, then you should expect such an error.

Adding such an overload to Attack ought to suffice. For example, using a simple struct for an Attack :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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