簡體   English   中英

刪除重復項的有效方法

[英]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::setCompare的第二個模板參數默認為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM