簡體   English   中英

在結構中為另一個結構的2個對象定義運算符<

[英]Define Operator < in struct for 2 objects of another struct

我在C ++中有一個小問題,希望您能為我提供幫助。

我想定義一個結構myPoint。 該結構應該能夠比較類型點(定義為對)中的兩個對象。 我希望myPoint的每個“實例”都能夠自己比較兩個點。 這是我嘗試編寫的代碼:

typedef pair<int,int> point;
struct myPoint{
    point p;
    inline bool operator<( point x, point y ){
    return !ccw(p,x,y);
}

因此,每個myPoint在比較兩個點x,y時都應考慮自己的點p。 我得到的(翻譯)錯誤是

"error C2804:  Binary Operator '<' has too much Arguments/Parameters"

從語法上講,僅使該操作符具有一個點似乎是可能的,我想它會將一個點與myPoint進行比較,但這不是應該的。 問題的背景是,我想使用預定義的排序函數對點向量進行排序,並希望將myPoint對象作為排序“函數”。

我認為(也許)您想做的是寫一個函子

struct myPoint
{
    myPoint(point p) { this->p = p; }
    bool operator()(point x, point y) const
    {
        return !ccw(p,x,y);
    }
    point p;
};

函子可以作為第三個參數傳遞給std :: sort。

std::sort(vec.begin(), vec.end(), myPoint(p));

不過,我有疑問,假設ccw表示逆時針方向,我認為這不是有效的排序條件。

<僅使用一個參數定義重載。 正如@KonradRudolph所指出的,重載<在這種情況下是沒有意義的,因為您無法在排序或其他任何操作中使用它

typedef pair<int,int> point;
struct myPoint{
    point p;
    bool smaller(const point &a, const point &b)
    {
        return !ccw(p,a,a)
    }
};

該片段應為您說明基本內容:

#include <utility>

typedef std::pair<int,int> point;

bool less(const point& p1, const point& p2)
{
    return (p1.first < p2.first) ||
           ((p1.first == p2.first) && (p1.second == p2.second));
}

struct myPoint {
    point p;
    inline bool operator < (const point& p2) {
        return less(p, p2);
    }
};

int main()
{
    return 0;
}
  1. 您尚未“關閉”運算符<。
  2. 如果像這樣的方法,運算符<僅需要一個參數。
  3. 使用常量引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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