结构体的三种排序方式

 1 #include<bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 const int N = 1e5;
 6 
 7 struct node{
 8     int key;
 9     int value;
10     //方法一 重载小于运算符
11     bool operator < (const node &rhs) const{
12         return key < rhs.key || key == rhs.key && value > rhs.value;
13     } 
14 }st[N];
15 
16 //方法二 手写cmp 
17 bool cmp(const node &a, const node &b){
18     return a.key < b.key || a.key == b.key && a.value > b.value;
19 }
20 
21 //方法三 定义一个结构体,重载()运算符  让他类似于一个函数的调用 
22 struct cmp2{
23     
24     bool operator () (const node &a, const node &b) const{
25         return a.key < b.key || a.key == b.key && a.value > b.value;
26     }
27 };
28 
29 int main(){
30     
31     for(int i=1; i<=5; i++){
32         st[i].key = 1;
33         st[i].value = 5 - i;
34     }
35     for(int i=6; i<=10; i++){
36         st[i].key = i;
37         st[i].value = 10 - i;
38     }
39     //sort(st+1,st+1+10); 方法一 
40     //sort(st+1,st+1+10,cmp); 方法二 
41     //sort(st+1,st+1+10,cmp2()); 方法三 
42     for(int i=1; i<=10; i++){
43         cout << st[i].key << " " << st[i].value << endl;
44     }
45     return 0;
46     
47 }

猜你喜欢

转载自www.cnblogs.com/zhangqiling/p/12425697.html