做题日记 之 EXCEL排序(HDU-1862)

本文介绍如何使用C++定义结构体`Student`,并创建一个自定义的比较函数`cmp`,以便根据题目要求的不同条件对学生成绩进行排序。通过`sort`函数实现对学生信息的按ID、姓名或分数进行排序的示例。
摘要由CSDN通过智能技术生成

前言

HDU - 1862

 


定义结构体,再写一个比较函数就可以使用sort排序了

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

struct Student {
    string id;
    string name;
    int score;
};

int N, C;
bool cmp(Student a, Student b) {
    if (C == 1)
        return a.id < b.id;
    else if (C == 2) {
        if (a.name != b.name)
            return a.name < b.name;
        return a.id < b.id;
    }
    else if (C == 3) {
        if (a.score != b.score)
            return a.score < b.score;
        return a.id < b.id;
    }
}

int main() {
    int i_case = 0;
    while (scanf("%d %d", &N, &C) && N && C) {
        i_case++;
        vector<Student> students;
        for (int i = 0; i < N; i++) {
            Student tmp;
            cin >> tmp.id >> tmp.name >> tmp.score;
            students.push_back(tmp);
        }
        sort(students.begin(), students.end(), cmp);
        printf("Case %d:\n", i_case);
        for (int i = 0; i < N; i++)
            cout << students[i].id << " " << students[i].name << " " << students[i].score << endl;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

低冷dl

喜欢您来~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值