sort(); 位於C++
頭文件 #include<algorithm>中
數組排序(從小到大,從大到小)
結構體排序(數字參數從大到小...字符串為參數 字典序....)
代碼示例:(直接復制運行對比結果看源碼)
#include<iostream>
#include<algorithm>
using namespace std;
// 對下文所有函數進行聲明
struct node
{
int sum;
char s[10];
} str[10];
int cmpn1(node a,node b)
{
return a.sum>b.sum;
}
int cmpn2(node a,node b)
{
return a.s>b.s;
}
int cmp(int a,int b)
{
return a>b;
}
int main()
{
int a[100]= {1,3,6,9,4,2,3,6,7,10};
//一共10個
cout<<"a數組最初狀態\n"<<endl;
for(int i=0; i<10; i++)
cout<<a[i]<<endl;
//需要排序首位置加上需排序的位長
cout<<"默認是從大到小排序\n"<<endl;
sort(a,a+10);
for(int i=0; i<10; i++)
cout<<a[i]<<endl;
cout<<endl;
cout<<"引入cmp()從大到小\n"<<endl;
sort(a,a+10,cmp);
for(int i=0; i<10; i++)
cout<<a[i]<<endl;
cout<<endl;
// 結構體賦值
for(int i=0; i<10; i++)
{
str[i].sum=i;
str[i].s[0]='a'+i;
}
cout<<"以sum為參數 調用cmp1進行從大到小\n"<<endl;
sort(str,str+10,cmpn1);
for(int i=0; i<10; i++)
cout<<str[i].sum<<endl;
cout<<endl;
cout<<"經過sum作為參數排序后,字符串目前狀態\n"<<endl;
for(int i=0; i<10; i++)
cout<<str[i].s<<endl;
cout<<endl;
cout<<"以s為參數 調用cmp2進行字典序\n"<<endl;
sort(str,str+10,cmpn2);
for(int i=0; i<10; i++)
cout<<str[i].s<<endl;
cout<<endl;
return 0;
}