sort 函数用法(日志11)

1.头文件

在C++中使用sort()函数需要使用#include<algorithm>头文件

algorithm意为“算法”,是C++的标准模板库中最重要的头文件之一。

2.基本使用方法

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;
	
} 

3.自定义排序

bool cmp(int x,int y){
	return x%10>y%10 ;
}

将这个cmp函数作为参数传入sort()中即可实现了上述排序需求

#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int x,int y){
	return x % 10 > y % 10;
}

int main(){
	int num[10] = {65,59,96,13,21,80,72,33,44,99};
	sort(num,num+10,cmp);
	for(int i=0;i<10;i++){
		cout<<num[i]<<" ";
	}//输出结果:59 99 96 65 44 13 33 72 21 80
	
	return 0;
	
} 

4.对结构体排序

sort()也可以对结构体进行排序,比如定义一个结构体含有学生的姓名和成绩的结构体Student,然后按照每个学生的成绩从高到底进行排序。首先将结构体定义为:

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;
}

完整代码:

#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;
	}
	
	return 0;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 12:10
直接上图
牛客13578115...:改得一般,不值80
点赞 评论 收藏
分享
07-07 17:06
已编辑
深圳技术大学 golang
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务