利用sort函数对结构体进行排序

划重点:添加cmp(函数名可更改)函数,根据需要定制排序

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

struct Node {
	int a;
	int b;
};

int cmp(const Node &first, const Node &second) { //根据需要定制排序 
	return first.a > second.a; //根据a从大到小排列
	//return first.b < second.b; //根据b从小到大排列
	/*
	if (first.a == second.a) return first.b > second.b;
	else first.a > second.a;
	*/ 
}

int main() {
	
	Node node[5];
	
	for (int i = 0; i < 5; i++) {
		scanf("%d%d", &node[i].a, &node[i].b);
	}
	
	sort(node, node+5, cmp);
	
	for (int i = 0; i < 5; i++) {
		printf("%d %d\n", node[i].a, node[i].b);
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40571331/article/details/83002373