简体   繁体   中英

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)

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

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