[英]Efficient way to remove duplicates
按照該線程的答案“ 刪除重復項和對向量進行排序的最有效方法是什么? ”。 我寫了下面的代碼,但是我收到一個錯誤,抱怨no match for 'operator<' (operand types are 'const connector' and 'const connector')
等等...
connector
是我自己編寫的類,基本上是具有兩個幾何點的線。 uniqCntrs
是一個std :: vector。 它具有100%的重復項,這意味着每個元素都有一個重復項, uniqCntrs
的大小很大。 我的代碼有什么問題,以及如何處理這種情況?
std::set<connector> uniqCntrsSet;
for(unsigned int i = 0; i < uniqCntrs.size(); ++i )
{
uniqCntrsSet.insert(uniqCntrs[i]);
}
uniqCntrs.assign(uniqCntrsSet.begin(), uniqCntrsSet.end());
我不知道如何為連接器類定義<
運算符。 我的意思是說一條線小於另一條線在物理上是沒有意義的。
來自cppreference :
std::set
是一個關聯容器,其中包含一組Key類型的唯一對象的排序集合。 使用鍵比較功能“比較”完成排序。
std::set
, Compare
的第二個模板參數默認為std::less
,默認情況下,它將對象與operator<
進行比較。 要解決此問題,您只需為Key
類型(即connector
)定義operator<
即可。
實際上, operator<
僅用於有效地排序std::set
使用的地圖。 它沒有任何意義。 唯一的要求是運算符必須滿足嚴格的弱序的標准數學定義。
看這一點的例子:
class Point
{
public:
Point(int x, int y) : x(x), y(y) {
}
public:
bool operator==(const Point &other) const {
return x==other.x && y==other.y;
}
bool operator!=(const Point &other) const {
return !operator==(other);
}
bool operator<(const Point &other) const {
if (x==other.x) {
return y<other.y;
} else {
return x<other.x;
}
}
private:
int x;
int y;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.