【算法】结构体排序基础
1.一个结构体中有三个元素,按照其中一个元素进行升序排列:
先定义一个结构体:
struct node
{
int s;
int t;
int w;
}a[1005];
然后写排序代码:(cmp函数里面的排序方法可以自定义) (函数返回值可以统一为bool)
int cmp(node a, node b)
{
return a.s > b.s;
}
在main函数里面用sort进行排序:
sort(a, a+ n, cmp);
原理:按照其中一个元素的大小来控制两个结构体间谁大, sort实现快排。
测试代码:
#include<iostream>
#include<algorithm>
using namespace std;
struct node
{
int s;
int t;
}a[1005];
bool cmp(node a, node b)
{
return a.s > b.s;
}
int main()
{
a[0] = { 12, 5 };
a[1] = { 4,6 };
a[2] = { 76,9 };
sort(a, a + 3, cmp);
for (int i = 0; i < 3; i++)
{
cout << a[i].s << "\t" << a[i].t << endl;
}
return 0;
}
2:按分数从高到低输出上线考生的考号与分数,其间用1空格分隔。若有多名考生分数相同,则按他们考号的升序输出。
代码:
struct Student
{
char str[20]; //考生准考证号
char num[20]; //存题号
int sum; // 考生的最后得分
}student[100];
int cmp(Student a, Student b)
{
if(a.sum == b.sum)
{
return a.str < b.str;
}
return a.sum >b.sum;
}
sort(student, student+n, cmp);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)