2013-05-06 44 views
-1

我有一个类,构造函数如下:C++如何从类类型的向量中删除重复项?

myclass(int=0,string="",int=0,string="",int=0,int=0, 
     int=0,int=0,string="",int=0,int=0); 

vector<myclass>myvect; 

矢量进行排序,我试图删除重复 ,这是这种类型的元素的矢量不工作:

std::vector<myclass>::iterator it; 
    it=std::unique (myvect.begin(), myvect.end()); 
    myvect.resize(std::distance(myvect.begin(),it)); 

我得到这个错误

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

任何想法,为什么? 有什么办法可以从这个向量中删除重复?

+1

为'myclass'实现'operator =='? – Morwenn 2013-05-06 17:39:05

+1

一个简单的解决方案是实现您自己的相等运算符。 – 2013-05-06 17:39:08

回答

2

std::unique算法需要知道如何比较两个myclass对象是否相等。有两种方法可以做到这一点。首先是实施myclass::operator==。第二种方法是将二进制谓词传递给std::unique

std::unique (myvect.begin(), myvect.end(), 
      [](const myclass& a, const myclass& b) { 
       return /* some expression to test equality */; 
      }); 
+0

非常感谢,我的问题是错误的我的意思是如何删除重复。 – Sonicpath 2013-05-06 18:05:56

1

你可能没有实现myclass::operator==

1

为了应用unique算法,您需要为您的类myclass过载operator ==

std::unique文档引用:

该函数使用运算符==,比较对元件(或预解码值,在版本(2))。