Michał Bieńko
Michał Bieńko

Reputation: 1

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>

Upvotes: 0

Views: 102

Answers (2)

john
john

Reputation: 87959

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.

Upvotes: 3

Chris Uzdavinis
Chris Uzdavinis

Reputation: 6131

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

Upvotes: 2

Related Questions