(一)文字描述
当我们使用sort对结构体进行排序时,我们要首先自己编写一个排序函数,在排序函数中,规定好排序的优先顺序;
(二)伪代码展示
1.先写头文件:
#include <algorithm> //调用sort函数必备;
或者直接编写c++万能头文件:
#include<bits/stdc++.h>
2.编写题目所需要的结构体:
struct Num //设置结构体名称为 Num
{
int x;
int y;
};
3.编写针对于结构体的比较函数:
bool cmp(Num a,Num b) //这里注意 a b 均为结构体类型
{
if(a.x!=b.x)
{
return a.x>b.x; //第一优先级:按照x从大到小排序;
}
else //当a和b相同时,使用第二优先级排序;
{
return a.y>b.y; //第二优先级,按照y从大到小排序;
}
}
4.main函数实现排序:
int main()
{
Num num[n];
sort(num,num+n,cmp); //对结构体的n个进行排序,排序准则调用 cmp函数
return 0;
}
(三) 典型例题分析:
附一道使用结构体的sort排序的CCF原题,以便于更好的理解,将原文链接放在这里。
https://blog.csdn.net/weixin_43978384/article/details/108121089