C++ 结构体排序

在这里插入图片描述

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

typedef struct city
{
    string name;
    double first;
    double second;
    double third;
    double all;
    double part;
}city;

bool comparsion(city a, city b){
    return a.all > b.all;
}

int main()
{
    int n;
    cin >> n;
    vector<city> array(n);
    for(int i = 0; i < n; i++){
        cin >> array[i].name >> array[i].first >> array[i].second >> array[i].third;
        array[i].all = array[i].first + array[i].second + array[i].third;
        array[i].part = array[i].third / array[i].all;
    }

    sort(array.begin(), array.end(), comparsion);

    string name_third;
    for(int i = 0; i < 3; i++){
        int max_third = 0;
        if (array[i].part > max_third){
            max_third = array[i].part;
            name_third = array[i].name;
        }
        cout << array[i].name << " " << array[i].first << " " << array[i].second << " " << array[i].third << " " << array[i].all  << endl;
    }
    cout << array[0].name << " " << name_third;
    return 0;
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C语言中,可以通过重载"<"比较运算符或者使用内置的比较函数来对结构体数组进行排序。这里提供了三种不同的方法来实现结构体数组的排序。 第一种方法是在结构体内部重载"<"比较运算符。我们可以定义一个结构体node,其中包含两个整型成员x和y。在结构体内部,我们重载"<"比较运算符,通过比较x和y的值来决定结构体排序方式。然后我们声明一个结构体数组a,并将其元素按照我们定义的排序规则进行排序。这种方法可以避免使用sort函数,直接在结构体内部进行排序。 第二种方法是使用内置的比较函数less<type>或greater<type>。我们可以使用sort函数对结构体数组a进行排序,通过传入less<int>()或者greater<int>()来指定排序的顺序,从小到大或者从大到小。这种方法可以简化代码,但需要使用sort函数。 第三种方法是通过重载"<"比较运算符来规定sort排序方法。与第一种方法类似,我们定义一个结构体node,并在结构体外部定义友元函数operator<来重载"<"比较运算符。在函数内部,我们比较两个结构体的x和y值,并根据比较结果决定排序方式。然后我们声明一个结构体数组a,并调用sort函数对数组进行排序。 总之,在C语言中,我们可以通过重载"<"比较运算符或者使用内置的比较函数来对结构体数组进行排序。具体的方法取决于个人的需求和偏好。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [C++结构体如何排序](https://blog.csdn.net/Ivoritow/article/details/129231105)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值