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

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

我有以下 C++ class,

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

在我的主要功能中,我有一个包含 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 };

现在我想使用以下方法调用从 rvec 中删除一项,

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

但是我得到了这个错误:

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

您需要为您的自定义数据结构重载运算符== rec

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

因为 remove 通过运算符比较值==