C++题解之 蓝桥杯 算法提高 成绩排序

题目:

题目链接
Problem
这题官方给了点小提示:结构体
当然,对类(class)非常擅长的 我怎么可能直接写 struct 呢?
上来先敲个 class,运算符重载 operator,重载>,用来调用 sort(),把构造和析构写好,顺便再重载个IO


sort(): 头文件 algorithm 中的函数,用来快速排序,详细教程点击跳转(这里借一下别人的教程)


C++ 代码如下:

// 出处:https://blog.csdn.net/sjc_0910/article/details/104144750
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
// class
class Student {
private:
    int math, english, chinese;
public:
    int id;
    friend istream& operator>> (istream&, Student&);
    friend ostream& operator<< (ostream&, Student&);
    bool operator> (const Student&) const;
    Student(int c = 0, int m = 0, int e = 0, int i = 0): math(m), chinese(c), english(e), id(i) {}
    virtual ~Student() {}
};
// 重载 IO流 运算符
istream& operator>> (istream& is, Student& x) {
    is >> x.math >> x.english >> x.chinese;
    return is;
}
ostream& operator<< (ostream& os, Student& x) {
    os << x.math << ' ' << x.english << ' ' << x.chinese << ' ' << x.id;
    return os;
}
// 重载 > 运算符
bool Student::operator> (const Student& y) const {
    const Student &x = *this;
    // 非 friend 的 operator 重载函数,往往有着隐藏形参 this,this 是一个指向
    // 调用本函数的对象的一个指针,所以声明引用类型时,需要对其进行解引用
    // 看了上面的注释,是不是很晕?
    if (x.math > y.math) return true;
    if (x.math == y.math) {
        if (x.english > y.english) return true;
        if (x.english == y.english) {
            if (x.chinese > y.chinese) return true;
            if (x.chinese == y.chinese) {
                if (x.id < y.id) return true;
            }
        }
    }
    return false;
}
int main() {
    ios::sync_with_stdio(false); // IO流优化,详情请见我的博客:
    // https://blog.csdn.net/sjc_0910/article/details/104128595
    int n;
    cin >> n;
    Student a[n];
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        a[i].id = i + 1;
    }
    sort(a, a + n, greater<Student>());
    // 如果你想知道 greater<Type>() 是什么,请访问(这是别人的教程):
    // https://blog.csdn.net/cnd2449294059/article/details/77090174
    for (int i = 0; i < n; i++)
        cout << a[i] << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

jcShan709

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值