2016-11-23 31 views
-1

我有以下的C++类,如何从C++中的对象矢量中删除一个项目?

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

而且在我的主要功能我有rec对象的vector,

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)

+3

您需要实现==操作符()为REC类以允许rec对象之间的比较。这是删除用来查找与r_remove匹配的条目的内容。 –

+0

如果您无法为您的类实现'operator ==',您也可以尝试['std :: remove_if'](http://en.cppreference.com/w/cpp/algorithm/remove) – StoryTeller

+0

将来的参考你应该注意到每一个算法都是它接受的类型的一组要求。阅读文档并了解这些要求是什么。 [cppreference](http://en.cppreference.com/w/cpp/algorithm)是书签的好地方。 – StoryTeller

回答

5

你需要重载==操作符为您的自定义数据结构rec

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

因为remove通过运营商==比较值

+0

谢谢@ Starl1ght,它工作完美。我只需要将类名“rec”添加到运算符定义中:bool operator ==(const rec&rhs) – MHS2015

+0

@ MHS2015是的,有点mistypo,对不起:) – Starl1ght

相关问题