简体   繁体   English

如何从C ++中的对象向量中删除一项?

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

I have the following C++ class, 我有以下C ++类,

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

And in my main function I have a vector with rec objects, 在我的主要功能中,我有一个带有rec对象的向量,

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删除一项:

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) C2678:二进制'==':未找到采用'rec'类型的左操作数的运算符(或没有可接受的转换)

You need to overload operator== for your custom data structure rec 您需要为您的自定义数据结构rec重载operator ==

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== 因为remove通过operator ==比较值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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