C++ sort函数自定义排序规则

在使用vector容器时经常要进行排序,使用排序函数sort非常方便,但是之前都是简单调用sort(v.begin(), v.end());没有自定义排序规则使用sort函数的额第三个参数,下面对sort总一个简单总结。

头文件:#include <algorithm>

第三个参数compare,是个自定义的比较函数的指针,名字可以随便命名;原型如下:

 bool cmp const Type1 &aconst Type2  b ;

简单说来就是:

比较a和b,如果是想升序,那么就定义当a<b的时候返回true;

                  如果是想降序,那么就定义当a>b的时候返回true;

代码举例

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

bool cmp(const int& a, const int& b)
{
	return a > b; //从大到小排序
}

int main()
{
	int a[10] = {2, 3, 30, 305, 32, 334, 40, 47, 5, 1};
	vector<int> nums(a, a + 10);

	sort(nums.begin(), nums.end(), cmp);

	for(auto x : nums)
		cout << x;
	cout << endl;

	system("pause");
	return 0;
}

 

  • 15
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值