STL标准模板库中的sort函数

代码骑士
优质创作者: 游戏开发技术领域
2023-01-03 13:37:02

一、函数原型:

使用第一个版本是对[first,last)进行升序排序,默认操作符为"<",第二个版本使用comp函数进行排序控制,comp包含两个在[first,last)中对应的值,如果使用"<"则为升序排序,如果使用">"则为降序排序。

二、使用方法:

使用sort函数需要引用头文件

#include<algorithm>

和标准命名空间std

(写法:using namespace std或std::sort)

三、用法实例:

默认升序排序:

#include<stdio.h>
#include<algorithm>

int main()
{
	int c=100;//船载重量 
	int w[10]={10,20,35,50,18,17,26,9,8,1};//古董重量数组 
	std::sort(w,w+10);//默认将w数组按从小到大排序 
	for(int i=0;i<10;i++)
		printf("%d,",w[i]); 
	return 0;
} 

自定义降序排序:

#include<stdio.h>
#include<algorithm>

//自动以排序规则
bool comp(int a,int b){//降序排序 
	return a>b;
} 

int main()
{
	int c=100;//船载重量 
	int w[10]={10,20,35,50,18,17,26,9,8,1};//古董重量数组 
	std::sort(w,w+10,comp);//自定义将w数组按从大到小排序 
	for(int i=0;i<10;i++)
		printf("%d,",w[i]); 
	return 0;
} 

 

...全文
2025 回复 打赏 收藏 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

5

社区成员

发帖
与我相关
我的任务
社区描述
考研408:数据结构、计算机组成原理、操作系统、计算机网络
学习方法考研面试 其他
社区管理员
  • 代码骑士
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧