c++-algorithm 头文件排序sort

本文详细介绍了C++标准模板库(STL)中的排序函数sort及其相关函数,包括stable_sort、partial_sort等,并提供了如何使用这些函数及自定义比较函数的具体示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

想起来自己天天排序排序,冒泡啊,二分查找啊,结果在STL中就自带了排序函数sort,qsort,总算把自己解脱了~

std::sort()函数的功能很强大,且可以对类,结构体等元素进行排序。C++sort参考手册

所以自己总结了一下,首先看sort函数见下表:参考csdn

函数名功能描述
sort对给定区间所有元素进行排序
stable_sort对给定区间所有元素进行稳定排序
partial_sort对给定区间所有元素部分排序
partial_sort_copy对给定区间复制并排序
nth_element找出给定区间的某个位置对应的元素
is_sorted判断一个区间是否已经排好序
partition使得符合某个条件的元素放在前面
stable_partition相对稳定的使得符合某个条件的元素放在前面

 

要使用此函数只需用#include <algorithm> 

sort即可使用,语法描述为:

sort(begin,end),表示一个范围,例如:

  1. #include<iostream>  
  2. #include<algorithm>  
  3. #include<string>  
  4. using namespace std;  
  5. int main()  
  6. {  
  7.     int a[10]={9,12,17,30,50,20,60,65,4,49};  
  8.     sort(a,a+10);  
  9.     for(int i=0;i<10;i++)  
  10.         cout<<a[i]<<' ';  
  11.     cout<<endl;  
  12.     return 0;  
  13. }  
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int main()
{
	int a[10]={9,12,17,30,50,20,60,65,4,49};
	sort(a,a+10);
	for(int i=0;i<10;i++)
		cout<<a[i]<<' ';
	cout<<endl;
	return 0;
}
2)自己编写一个比较函数来实现,接着调用三个参数的sort:sort(begin,end,compare)就成了。对于list容器,这个方法也适用,把compare作为sort的参数就可以了,即:sort(compare).

  1. #include<iostream>  
  2. #include<algorithm>  
  3. #include<string>  
  4. using namespace std;  
  5. bool compare(int a,int b)  
  6. {  
  7.     return a<b;   //默认升序排列,如果改为return a>b,则为降序  
  8. }  
  9. bool compare_decrease(int a,int b)  
  10. {  
  11.     return a>b;   //从大到小的排列  
  12. }  
  13. int main()  
  14. {  
  15.     int a[10]={9,12,17,30,50,20,60,65,4,49};  
  16.     sort(a,a+10);  
  17.     for(int i=0;i<10;i++)  
  18.         cout<<a[i]<<' ';  
  19.     cout<<endl;  
  20.     sort(a,a+10,compare_decrease);  
  21.     for(int i=0;i<10;i++)  
  22.         cout<<a[i]<<' ';  
  23.     cout<<endl;  
  24.     return 0;  
  25. }  
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
bool compare(int a,int b)
{
	return a<b;   //默认升序排列,如果改为return a>b,则为降序
}
bool compare_decrease(int a,int b)
{
	return a>b;   //从大到小的排列
}
int main()
{
	int a[10]={9,12,17,30,50,20,60,65,4,49};
	sort(a,a+10);
	for(int i=0;i<10;i++)
		cout<<a[i]<<' ';
	cout<<endl;
	sort(a,a+10,compare_decrease);
	for(int i=0;i<10;i++)
		cout<<a[i]<<' ';
	cout<<endl;
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值