我是靠谱客的博主 重要丝袜,这篇文章主要介绍按结构体某一字段对结构体数组进行排序(C++),现在分享给大家,希望可以做个参考。

【问题描述】
在具体应用中,有时需要按某一字段对结构体数组各元素进行排序输出。如何解决?
例如,现有一结构体Person,它由name,age,height等三个字段构成。
目前已经构建了结构体数组,现在要求按字段height升序排序(或降序排序)的顺序输出结构体数组各元素。若某些元素的字段height相等,则需对这些元素的字段name升序排序(或降序排序),但不能影响这些元素在整体输出中的相对位置。


【解决方法】
需要自定义函数up()、down()并调用。详细内容如下:
自定义的结构体Person的内容如下:

复制代码
1
2
3
4
5
struct Person { string name; int age; float height; };

自定义的比较函数up()、down()的内容如下:

复制代码
1
2
3
4
5
6
7
8
9
10
int up(Person u,Person v) { //ascending by height if(u.height==v.height) return u.name<v.name; //If equal,ascending by name return u.height<v.height; } int down(Person u,Person v) { //descending by height if(u.height==v.height) return u.name>v.name; //If equal,descending by name return u.height>v.height; }

在主函数中的调用方法如下:

复制代码
1
2
3
sort(p,p+n,up); //Sort the structured array p by ascending field height sort(p,p+n,down); //Sort the structured array p by descending field height


【算法实例】

复制代码
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <bits/stdc++.h> using namespace std; const int maxn=1005; struct Person { string name; int age; float height; }; int up(Person u,Person v) { //ascending by height if(u.height==v.height) return u.name<v.name; //If equal,ascending by name return u.height<v.height; } int down(Person u,Person v) { //descending by height if(u.height==v.height) return u.name>v.name; //If equal,descending by name return u.height>v.height; } int main() { Person p[maxn]; int n; cin>>n; for(int i=0; i<n; i++) { cin>>p[i].name>>p[i].age>>p[i].height; } sort(p,p+n,up); //Sort the structured array p by ascending field height //sort(p,p+n,down); cout<<endl; for(int i=0; i<n; i++) { cout<<p[i].name<<" "<<p[i].age<<" "<<p[i].height<<endl; } return 0; } /* in: 7 Tom 3 27.2 Mary 16 50.6 Jim 8 30.9 Bob 60 50.6 Wood 21 72.8 Alice 17 49.3 Kite 2 21.1 out: Kite 2 21.1 Tom 3 27.2 Jim 8 30.9 Alice 17 49.3 Bob 60 50.6 Mary 16 50.6 Wood 21 72.8 */



 

最后

以上就是重要丝袜最近收集整理的关于按结构体某一字段对结构体数组进行排序(C++)的全部内容,更多相关按结构体某一字段对结构体数组进行排序(C++)内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部