使用前需要引用头文件#include<algorithm>
sort(begin, end, cmp)
sort()函数可以对给定区间所有元素进行排序。它有三个参数sort(begin, end, cmp),其中begin为指向待sort()的数组的第一个元素的指针,end为指向待sort()的数组的最后一个元素的下一个位置的指针,cmp参数为排序准则,cmp参数可以不写,如果不写的话,默认从小到大进行排序。如果我们想从大到小排序可以将cmp参数写为greater<int>()就是对int数组进行排序,当然<>中我们也可以写double、long、float等等。如果我们需要按照其他的排序准则,那么就需要我们自己定义一个bool类型的函数来传入。
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int num[10] = {6,5,9,1,2,8,7,3,4,0};
sort(num,num+10,greater<int>());
for(int i=0;i<10;i++){
cout<<num[i]<<" ";
}//输出结果:9 8 7 6 5 4 3 2 1 0
return 0;
}
自定义排序
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <string>
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()
{
string n;
int s;
Student student[3];
for (size_t i = 0; i < 3; i++)
{
cin >> n >> s;
student[i] = Student(n, s);
}
sort(student, student + 3, cmp_score);
for (size_t i = 0; i < 3; i++)
{
cout << student[i].name << " " << student[i].score << endl;
}
}
2763





