MHS2015 MHS2015 - 9 days ago 4
C++ Question

How to remove one item from a vector of objects in c++?

I have a class in C++ for example "rec" that is defined as following,

class rec
{
public:
int width;
int height;
};


In my main function I have a vector of rec,

rec r1,r2,r3;
r1.height = r1.width = 1;
r2.height = r2.width = 2;
r3.height = r3.width = 3;

vector<int> vec = { 1,2,3,4,5 };


I define a vector of rec,

vector<rec> rvec = { r1,r2,r3 };


Know I want to erase one item from rvec by this command,

rvec.erase(remove(rvec.begin(), rvec.end(), r_remove), rvec.end());


But I got this error:


C2678: binary '==': no operator found which takes a left-hand operand
of type 'rec' (or there is no acceptable conversion)

Answer

You need to overload operator== for your custom data structure rec

class rec
{
public:
    int width;
    int height;
    bool operator==(const rec&  rhs) {
        return (width == rhs.width) && (height == rhs.height);
    }
};

since remove compares values via operator==

Comments