C++自定义排序

C++自定义排序

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

bool compare1(const int& a, const int& b)
{
	return a < b;  // 升序 
}

bool compare2(const int& a, const int& b)
{
	return a > b;  // 降序 
}

bool compare3(const int& a, const int& b)
{
	string sa = to_string(a);
	string sb = to_string(b);
	return stoi(sa+sb) < stoi(sb+sa);
}

int main(int argc, char* argv[])
{
	// 1
	vector<int> nums{2, 4, 7, 1, 9, 3};
	sort(nums.begin(), nums.end());  // sort默认是升序排序
	for (auto num : nums)
		cout << num << " ";
	cout << endl;
	// 2 
	vector<int>{2, 4, 7, 1, 9, 3}.swap(nums);
	sort(nums.begin(), nums.end(), compare1);  // 升序
	for (auto num : nums)
		cout << num << " ";
	cout << endl;
	// 3
	vector<int>{2, 4, 7, 1, 9, 3}.swap(nums);
	sort(nums.begin(), nums.end(), compare2);  // 降序
	for (auto num : nums)
		cout << num << " ";
	cout << endl;
	// 4 
	// 给定一个整数数组,如{23, 4, 12, 34, 123}, 把它们连起来组成最小的数。
	// 如 {23, 4} 输出{23, 4},因为234比423小
	// 如 {23, 4, 12} 输出{12, 23, 4},因为12234最小。
	vector<int>{23, 4, 12, 34, 123}.swap(nums);
	sort(nums.begin(), nums.end(), compare3);  // 自定义排序
	for (auto num : nums)
		cout << num << " ";
	cout << endl;
	return 0;
}
/*
如果在类中自定义sort排序,compare函数需要是static,使用方式为&ClassName::compare
*/
class Solution
{
public:
	// cons, decons
	static bool compare(const int& a, const int& b)  // static
	{
		return a > b;
	}
	void fun(){
		/*
		...
		*/
		sort(vec.begin(), vec.end(), &Solution::compare);  // &Solution::compare
	}
private:
	std::vector<int> vec;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值