按结构体某一字段对结构体数组进行排序(C++)

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


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

struct Person {
	string name;
	int age;
	float height;
};

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

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;
}

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

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


【算法实例】

#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
*/



 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值