Search code examples
c++vectorerase

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


I have the following C++ class,

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

And in my main function I have a vector with rec objects,

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

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

Now I want to erase one item from rvec with the following method call,

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)


Solution

  • 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==