C++ 结构体排序

C++ 结构体排序

引入头文件

#include<algorithm>

结构体

bool compare(const node &x, const node &y) {
	return x.v > y.v;
}

当用 大于号就是从大到小排序

用小于号就是从小到大排序

sort 函数

sort(branch+1,branch+m+1,compare);

完整代码

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

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中,结构体排序练习通常涉及到如何使用标准库中的算法对包含自定义数据类型的结构体数组或容器进行排序。这里我们可以举一个简单的例子,假设有一个名为`Student`的结构体,包含`name`和`age`两个成员: ```cpp struct Student { std::string name; int age; }; ``` 你可以用以下几种方法对`Student`结构体数组进行排序: 1. **直接排序:**如果年龄是排序的主要依据,你可以定义一个比较函数(`compare`),然后使用`std::sort`函数: ```cpp bool compareStudents(const Student& s1, const Student& s2) { return s1.age < s2.age; } int main() { Student students[] = {{"Alice", 20}, {"Bob", 18}, {"Charlie", 22}}; std::sort(students, students + sizeof(students) / sizeof(students), compareStudents); // 现在students数组按年龄升序排列 } ``` 2. **使用STL算法:**如果你的结构体已经实现了`<`运算符,那么可以直接使用`std::stable_sort`: ```cpp bool studentLess(const Student& s1, const Student& s2) { return s1.age < s2.age; } int main() { std::vector<Student> students = {{"Alice", 20}, {"Bob", 18}, {"Charlie", 22}}; std::stable_sort(students.begin(), students.end(), studentLess); } ``` 3. **自定义比较器(C++11及以上):**也可以使用lambda表达式来创建一个可传递的比较器: ```cpp int main() { std::vector<Student> students = {{"Alice", 20}, {"Bob", 18}, {"Charlie", 22}}; std::sort(students.begin(), students.end(), [](const Student& s1, const Student& s2) { return s1.age < s2.age; }); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值