我是靠谱客的博主 重要丝袜,最近开发中收集的这篇文章主要介绍按结构体某一字段对结构体数组进行排序(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
*/



 

最后

以上就是重要丝袜为你收集整理的按结构体某一字段对结构体数组进行排序(C++)的全部内容,希望文章能够帮你解决按结构体某一字段对结构体数组进行排序(C++)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部