2013-05-06 108 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))。