sort函数详解

sort函数作为算法库内自带的排序算法,极大地减少了程序猿在编写排序所花的时间。要使用sort函数,只需引入头文件#include<algorithm>

函数写法为 sort(begin,end)

例如:

#include<algorithm>
#include<iostream>
using namespace std;

int main()
{
	int a[10] = { 5, 51, 1, 3, 9, -1, 10, 9, 4, 0 };
	sort(a, a + 10);
	cout << "after sort: ";
	for (int i = 0; i < 10; i++){
		cout << a[i] << ' ';
	}
	return 0;
}

输出结果为:

默认排序为升序排序,那么又怎样利用它进行降序排序呢?

1.为了满足不同情况排序的要求,sort函数在end后还可以加一个比较函数,即接受含三个参数的sort;

sort(begin,end,compare)

例如,为满足降序排序的需求

#include<algorithm>
#include<iostream>
using namespace std;

bool compare(int a, int b){
	return a > b;
}
int main()
{
	int a[10] = { 5, 51, 1, 3, 9, -1, 10, 9, 4, 0 };
	sort(a, a + 10,compare);
	cout << "after sort: ";
	for (int i = 0; i < 10; i++){
		cout << a[i] << ' ';
	}
	return 0;
}

输出结果为

2.对<进行运算符重载,因为sort主要是通过<来排序,在对类的排序中较为实用

3.利用functional标准库

其实c++标准库中已有现成可用的比较运算符,在头文件中引用include进来即可。

#include<functional>

其中functional提供了如下的基于模板的比较函数对象。

1.equal_to<type>:等于;

2.not_equal_to<type>:不等于;

3.greater<type>:大于;

4.greater_equal<type>:大于等于;

5.less<type>:小于;

6.less_equal<type:小于等于。

例如:

#include<algorithm>
#include<functional>
#include<iostream>
using namespace std;

int main()
{
	int a[10] = { 5, 51, 1, 3, 9, -1, 10, 9, 4, 0 };
	sort(a, a + 10,greater<int>());
	cout << "after sort: ";
	for (int i = 0; i < 10; i++){
		cout << a[i] << ' ';
	}
	return 0;
}

就完成了降序排序

  • 3
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值