sort函数,特好使的排序函数,以下是sort的几种用法:
头文件:#include<algorithm>
1、整型/浮点型排序:
int cmp(int a,int b)
{return a>b;}
int main()
{
int a[10]={1,3,4,2,5,6,9,8,7,0};
double b[10]={1.2,2.1,1.0,3.3,2.2,1.1,0.4,5.4,3.4,3.2};
sort(b,b+10);//从小到大
sort(a,a+10,cmp);//从大到小
for(int i=0;i<10;i++)
{printf("%d ",a[i]);}//0 1 2 3 4 5 6 7 8 9
printf("\n");
for(int i=0;i<10;i++)
{printf("%.1lf ",b[i]);}//0.4 1.0 1.1 1.2 2.1 2.2 3.2 3.3 3.4 5.4
printf("\n");
return 0;
}
?2、字符型排序:
char a[10101];
scanf("%s",a);//abcdfehsdhoe
sort(a,a+strlen(a)-1);
printf("%s",a);//abcddefhhose
return 0;
3、字符型数组排序:
string a[1001];
int n=10;
for(int i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
for(int i=0;i<n;i++)
cout<<a[i]<<endl;
//abcdefgh aaa
//dcdcdcdc aaaaaaaa
//abccefgh abccefgh
//abxdeddd ---> abcdefgh
//bcbcbcbc ---> abcdfeds
//abcdfeds abxdeddd
//awdrgyhj awdrgyhj
//xyz bcbcbcbc
//aaaaaaaa dcdcdcdc
//aaa xyz
?4、结构题排序:
struct rel
{
int a;
int b;
int r;
}info[100100];
int cmp(rel &a,rel &b)//这里以结构题里元素r排序
{return a.r<b.r;}
int main()
{
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d%d%d",&info[i].a,&info[i].b,&info[i].r);
sort(info,info+n,cmp);
for(i=0;i<n;i++)
printf("%d %d %d\n",info[i].a,info[i].b,info[i].r);
return 0;
}
5、对c++函数库(此处以vector为例)排序:
vector<int>b;
int n,i,x;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&x);
b.push_back(x);
}
sort(b.begin(),b.end());
vector<int>::iterator is;
for(is=b.begin();is!=b.end();is++)
printf("%d ",*is);
printf("\n");
|