Skip to content

定義比較規則

定義st與st之間如何互相比較
最簡單寫法是:

struct st{
    int x;
    string y;
    
    bool operator<(st other){
        if(x==other.x)return y<other.y;  //這裡的x其實就是第2行的int x
        return x<other.x;
    }

};

這個的函數名稱就叫做"operator<"
因為st other要避免產生其他新的變數,改成取別名st& other
因為要抱持好的編寫習慣,加上const,變成:

struct st{
    int x;
    string y;
    
    bool operator<(const st& other)const{
        if(x==other.x)return y<other.y;  //這裡的x其實就是第2行的int x
        return x<other.x;
    }

};

可以把other當作cmp的b(bool cmp(st a,st b);)所以放右邊,像是下面程式碼。

但是其實一般來說只需要定義<就好了,因為std::sort / set / map / priority_queue / lower_bound 都只需要比較小於就好。

題外話:lower_bound的等價是!(a < b) && !(b < a)

所以如果只寫 bool operator<(const st& other) const { return x < other.x; }{x=5, y="a"}{x=5, y="b"}set 看來是「等價」的

#include <bits/stdc++.h>
using namespace std;
#define nn "\n"


struct st{
    int x;
    string y;

    bool operator<(const st& other)const{
        if(x==other.x)return y<other.y;
        return x<other.x;
    }
    bool operator>(const st& other)const{
        if(x==other.x)return y>other.y;
        return x>other.x;
    }
    bool operator==(const st& other)const{
        return x==other.x&&y==other.y;
    }

};


int main() {
    vector<st>v;

    v.push_back({2,"4444"});
    v.push_back({3,"66"});
    v.push_back({1,"99"});
    v.push_back({4,"2222"});
    v.push_back({5,"111"});


    sort(v.begin(),v.end());


    for(int i=0;i<5;i++){
        cout<<v[i].x<<" "<<v[i].y<<"\n";
    }

}
1 99
2 44
3 66
4 22
5 11