我是靠谱客的博主 淡然身影,这篇文章主要介绍std::sort的妙用(1),现在分享给大家,希望可以做个参考。

有时候需要按照结构体中某项数值进行排序,而结构体中的其他数值则不能改变。例如,按照成绩的高低对学生进行排序,而学生这一结构体中包含了学号,姓名等其他信息。使用std::sort就很方便

CODE

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
struct edge{ int from, to, cost; }; bool comp(const edge &e1, const edge &e2) { return e1.cost < e2.cost; } void sortFun() { edge es[MAXVEX]; srand((unsigned)time(NULL)); int N = 9; for (int i = 0; i < N; ++i) { es[i].from = i; es[i].to = rand() % 9; es[i].cost = rand() % 28; } for (int i = 0; i < N; ++i) { printf("%d %d %dn", es[i].from, es[i].to, es[i].cost); } printf("************************n"); sort(es, es + N, comp); for (int i = 0; i < N; ++i) { printf("%d %d %dn", es[i].from, es[i].to, es[i].cost); } }


复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<stdio.h> #include<stdlib.h> #include <cstring> #include <cstdio> #include<iostream> #include<algorithm> using namespace std; struct t_stu { int age; int score; char name[104]; }; inline bool Cmp(const t_stu & a, const t_stu & b){ if(a.score == b.score){ if(strcmp(a.name, b.name) == 0){ return a.age > b.age; } return strcmp(a.name, b.name) > 0; } return a.score > b.score; } int main(void){ int n; t_stu tStuRec[1001], *tp; while(~scanf("%d", &n))//注意输入,OJ常用 { for(tp = tStuRec; n--; ++tp){ scanf("%s %d %d", tp->name, &tp->age, &tp->score); } sort(tStuRec, tp, Cmp); while(--tp >= tStuRec){ printf("%s %d %dn", tp->name, tp->age, tp->score); } } return 0; }


最后

以上就是淡然身影最近收集整理的关于std::sort的妙用(1)的全部内容,更多相关std::sort内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(49)

评论列表共有 0 条评论

立即
投稿
返回
顶部