1. 程式人生 > >c++ sort函數

c++ sort函數

pac mes for 定義 std turn 排列 out algorithm

sort() 函數包含在 <algorithm>頭文件裏。

需要三個參數,起始地址、結束地址、排序方法。

沒有第三個參數,默認從小到大排序:

 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 }

從大到小排序,增加比較函數:

#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{
     return a>b;
}
int main()
{
     int a[10]={9,6,3,8,5,2,7,4,1,0};
     for(int i=0;i<10;i++)
     cout
<<a[i]<<endl; sort(a,a+10,cmp) for(int i=0;i<10;i++) cout<<a[i]<<endl; return 0; }

自己定義了一個結構體node:

1 struct node
2 {
3   int a;
4   int b;
5   double c;
6 }

先按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 }

c++ sort函數