头文件:
在C++中使用sort()函数需要使用#include<algorithm>
头文件。
参数:
sort(begin, end, cmp)
begin:为指向待sort()的数组的第一个元素的指针
end:为指向待sort()的数组的最后一个元素的下一个位置的指针
cmp:排序准则,cmp参数可以不写,如果不写的话,默认升序排序;也可以将cmp参数写为greater<int>()
使用标准库函数:
sort(A,A+100,greater<int>());//降序排列
sort(A,A+100,less<int>());//升序排列
如:equal_to<Type>、not_equal_to<Type>、greater<Type>、greater_equal<Type>、less<Type>、less_equal<Type>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int num[6]={0,3,4,5,1,2};
sort(num,num+6,greater<int>());
for(int i=0;i<6;i++)
{
cout<<num[i]<<" ";
//输出5 4 3 2 1 0
}
}
自定义排序:
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int x,int y)
{
return x % 10 >y % 10;
}//按照个位的降序
int main()
{
int num[5]={90,33,28,39,76};
sort(num,num+5,cmp);
for(int i=0;i<5;i++)
{
cout<<num[i]<<" ";
}//39 28 76 33 90
}
结构体排序:
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
struct Student{
string name;
int score;
Student(){};
Student(string n,int s):name(n),score(s){}
};
bool cmp_score(Student x,Student y)
{
return x.score>y.score;
}
int main()
{
Student stu[3];
string n;
int s;
for(int i=0;i<3;i++)
{
cin>>n>>s;
stu[i]=Student(n,s);
}
sort(stu,stu+3,cmp_score);
for(int i=0;i<3;i++)
{
cout<<stu[i].name<<" "<<stu[i].score<<endl;
}
}
//输入
小金 12
小米 23
小王 33
//输出
小王 33
小米 23
小金 12