sort用法

1、sort(a,a+7) a表示要排序的首地址,数组名代表的就是一个数组的首地址,7是要排序的元素个数

1     int a[] = { 8,2,9,1,0,5,6 };
2     sort(a, a + 7);
3     for (int i = 0; i < 7; i++) {
4         cout << a[i] << " ";//0 1 2 5 6 8 9
5     }

 

2、sort(a+1,a+5) 表示将[a+1,a+5)区间中的元素排序

1     int a[] = { 8,2,9,1,0,5,6 };
2     sort(a+1, a + 5);
3     for (int i = 0; i < 7; i++) {
4         cout << a[i] << " ";//8 0 1 2 9 5 6
5     }

 

3、sort(a,a+7,greater<int>()) 按从大到小的顺序排列

  sort默认是按照从小到大的顺序排列的,greater表示更大的意思,即更大的数排在前面,<int>表示要排序的数组中的元素是int类型的

1     int a[] = { 8,2,9,1,0,5,6 };
2     sort(a, a + 7,greater<int>());
3     for (int i = 0; i < 7; i++) {
4         cout << a[i] << " ";//9 8 6 5 2 1 0
5     }

 

4、定义一个比较大小的函数cmp

 1 #include<iostream>
 2 #include<algorithm>
 3 using namespace std;
 4 bool cmp(int x, int y) {
 5     return x > y;//表示大的排在前面
 6 }
 7 int main() {
 8     int a[] = { 8,2,9,1,0,5,6 };
 9     sort(a, a + 7,cmp);
10     for (int i = 0; i < 7; i++) {
11         cout << a[i] << " ";//9 8 6 5 2 1 0
12     }
13 
14     return 0;
15 }

 

5、比较结构体大小

方法一:

 1 #include<iostream>
 2 #include<algorithm>
 3 using namespace std;
 4 struct A {
 5     int x;
 6     int y;
 7 };
 8 bool cmp(A m, A n) {
 9     return  m.y> n.y;//y更大的排在前面
10 }
11 int main() {
12     A a[] = { {1,3},{4,1},{5,9},{1,6},{8,2} };
13     sort(a, a + 5,cmp);
14     for (int i = 0; i < 5; i++) {
15         cout << "(" << a[i].x << "," << a[i].y << ")" << " ";
16         //(5,9) (1,6) (1,3) (8,2) (4,1)
17     }
18 
19     return 0;
20 }

方法二:

 1 #include<iostream>
 2 #include<algorithm>
 3 using namespace std;
 4 struct A {
 5     int x;
 6     int y;
 7     bool operator<(const A &s)const {
 8         return y > s.y;//y大的在此结构体中定义的‘<’的左边,sort中<左边的在前面
 9     }
10 };
11 int main() {
12     A a[] = { {1,3},{4,1},{5,9},{1,6},{8,2} };
13     sort(a, a + 5);
14     for (int i = 0; i < 5; i++) {
15         cout << "(" << a[i].x << "," << a[i].y << ")" << " ";
16         //(5,9) (1,6) (1,3) (8,2) (4,1)
17     }
18 
19     return 0;
20 }

 

 

posted @ 2019-11-24 21:44  lucky99  阅读(4304)  评论(0编辑  收藏  举报