c++ sort自定义排序

介绍

如何使用c++ STL中的sort函数去排序一些结构体类型的数据呢?
这里可以采用自定义比较函数的方法。

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

typedef struct
{
	int x;
	int y;
} point;
//从小到大排序,以x为主序,y为次序
bool cmp1(point &a, point &b)
{
	if (a.x == b.x)
	{
		return a.y < b.y;
	}
	return a.x < b.x;
}

//从大到小排序,以x为主序,y为次序
bool cmp2(point &a, point &b)
{
	if (a.x == b.x)
		return a.y > b.y;
	return a.x > b.x;
}
int main()
{
	int n = 10;
	point p[10];
	for (int i = 0; i < 10; i++)
	{
		p[i].x = rand() % 10 + 1;
		p[i].y = rand() % 10 + 1;
		cout << p[i].x << " " << p[i].y << endl;
	}
	cout << "the sort's result:............." << endl;
	sort(p, p + 10, cmp2);
	for (int i = 0; i < 10; i++)
		cout << p[i].x << " " << p[i].y << endl;
	return 0;
}

值得关注的地方就是两个cmp1cmp2函数,

  • cmp1希望用来实现从小到大排序

  • cmp2希望用来实现从大到小排序

补充:

突然想起个了注意事项,要记得把是否相等的判断写在大小判断的前面
image
顺序不可乱

posted @ 2022-06-11 15:24  请去看诡秘之主  阅读(271)  评论(0编辑  收藏  举报