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

题目:

题目链接
C++题解之 蓝桥杯 算法提高 成绩排序2_第1张图片
这题与成绩排序那题差不多,都可以用 class 实现,只要把成绩排序那题的代码改改就ok啦

成绩排序题解,点击跳转

// 出处:https://blog.csdn.net/sjc_0910/article/details/104145262
#include 
#include 
#include 
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() 是什么,请访问(这是别人的教程):
    // https://blog.csdn.net/cnd2449294059/article/details/77090174
    for (int i = 0; i < n; i++)
        cout << a[i] << endl;
    return 0;
}

你可能感兴趣的:(C++,题解,编程)