C++ sort()排序详解

头文件

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

sort()基本使用方法

sort()函数可以对给定区间所有元素进行排序。它有三个参数sort(begin, end, cmp)

其中begin为指向待sort()的数组的第一个元素的指针,end为指向待sort()的数组的最后一个元素的下一个位置的指针,cmp参数为排序准则,cmp参数可以不写,如果不写的话,默认从小到大进行排序

如果我们想从大到小排序可以将cmp参数写为greater<int>()就是对int数组进行排序,当然<>中我们也可以写double、long、float等等

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

自定义排序准则

上面我们说到sort()函数可以自定义排序准则,以便满足不同的排序情况。使用sort()我们不仅仅可以从大到小排或者从小到大排,还可以按照一定的准则进行排序。

比如说我们按照每个数的个位进行从大到小排序,我们就可以根据自己的需求来写一个函数作为排序的准则传入到sort()中。

我们可以将这个函数定义为:

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

相关推荐

  1. 冒泡排序详解

    2024-05-11 10:16:03       42 阅读
  2. 冒泡排序详解

    2024-05-11 10:16:03       26 阅读
  3. C++ sort()排序详解

    2024-05-11 10:16:03       11 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-11 10:16:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-11 10:16:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-11 10:16:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-11 10:16:03       20 阅读

热门阅读

  1. NSS刷题

    NSS刷题

    2024-05-11 10:16:03      13 阅读
  2. 新能源汽车为什么容易自燃

    2024-05-11 10:16:03       10 阅读
  3. vscode触发建议缓慢问题

    2024-05-11 10:16:03       15 阅读
  4. Linux下MySQL的用户与权限管理

    2024-05-11 10:16:03       11 阅读
  5. 蓝桥杯 算法提高 ADV-1169 区间覆盖问题 python AC

    2024-05-11 10:16:03       9 阅读
  6. VSCODE + SSH for PHP 配置

    2024-05-11 10:16:03       12 阅读
  7. MyBatis——MyBatis 核心配置文件

    2024-05-11 10:16:03       6 阅读
  8. 三生随记——耳机里的诅咒

    2024-05-11 10:16:03       8 阅读
  9. 2.mysql--备份恢复

    2024-05-11 10:16:03       10 阅读
  10. Spring Cloud LoadBalancer 4.1.2

    2024-05-11 10:16:03       9 阅读
  11. Acwing2024蓝桥杯并查集

    2024-05-11 10:16:03       15 阅读