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

题目:

题目链接
Problem
这题与成绩排序那题差不多,都可以用 class 实现,只要把成绩排序那题的代码改改就ok啦

成绩排序题解,点击跳转

// 出处:https://blog.csdn.net/sjc_0910/article/details/104145262
#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+x.chinese+x.english) > (y.math+y.chinese+y.english)) return true;
    if ((x.math+x.chinese+x.english) == (y.math+y.chinese+y.english)) {
        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.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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

jcShan709

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

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

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

打赏作者

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

抵扣说明:

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

余额充值