轉載自博主:九江鎮中https://www.cnblogs.com/jjzzx/
c++標准庫里的排序函數的使用方法
I)Sort函數包含在頭文件為#include<algorithm>的c++標准庫中,調用標准庫里的排序方法可以不必知道其內部是如何實現的,只要出現我們想要的結果即可!
II)Sort函數有三個參數:
(1)第一個是要排序的數組的起始地址。
(2)第二個是結束的地址(最后一位要排序的地址)
(3)第三個參數是排序的方法,可以是從大到小也可是從小到大,還可以不寫第三個參數,此時默認的排序方法是從小到大排序。
Sort函數使用模板:
Sort(start,end,排序方法)
下面就具體使用sort()函數結合對數組里的十個數進行排序做一個說明!
例一:sort函數沒有第三個參數,實現的是從小到大
1 #include<iostream>
2
3 #include<algorithm>
4 using namespace std;
5 int main()
6 {
7 int a[10]={9,6,3,8,5,2,7,4,1,0};
8 for(int i=0;i<10;i++)
9 cout<<a[i]<<endl;
10 sort(a,a+10);
11 for(int i=0;i<10;i++)
12 cout<<a[i]<<endl;
13 return 0;
14 }
例二
通過上面的例子,會產生疑問:要實現從大到小的排序腫么辦?
這就如前文所說需要在sort()函數里的第三個參數里做文章了,告訴程序我要從大到小排序!
需要加入一個比較函數 complare(),此函數的實現過程是這樣的
bool complare(int a,int b) { return a>b; }
這就是告訴程序要實現從大到小的排序的方法!
1 #include<iostream>
2 #include<algorithm>
3 using namespace std;
4 bool complare(int a,int b)
5 {
6 return a>b;
7 }
8 int main()
9 {
10 int a[10]={9,6,3,8,5,2,7,4,1,0};
11 for(int i=0;i<10;i++)
12 cout<<a[i]<<endl;
13 sort(a,a+10,complare);//在這里就不需要對complare函數傳入參數了,
14 //這是規則
15 for(int i=0;i<10;i++)
16 cout<<a[i]<<endl;
17 return 0;
18 }
假設自己定義了一個結構體node
1 struct node
2 {
3 int a;
4 int b;
5 double c;
6 }
有一個node類型的數組node arr[100],想對它進行排序:先按a值升序排列,如果a值相同,再按b值降序排列,如果b還相同,就按c降序排列。就可以寫這樣一個比較函數:
以下是代碼片段:
1 bool cmp(node x,node y)
2 {
3 if(x.a!=y.a) return x.a<y.a;
4 if(x.b!=y.b) return x.b>y.b;
5 return x.c>y.c;
6 }

