vector 存放对象的排序问题

我首先定义了一个student类 内有整型学号 整型分分数等数据
然后我想使用

vector<student> stu

中的sort函数进行排序 排序的根据是分数对vector进行降序排序
但是当我写出

sort(stu.rbegin(),stu.rend())

编译报错了
所以该如何仅根据每个对象中的分数进行排序呢

下面是我的代码

#include <bits/stdc++.h>
using namespace std;
class student
{
public:
    int no;
    int score;
    student(int No=0, int Score=0)
    {
        no = No;
        score = Score;
    }
};
int main()
{
    int no;
    int score;
    vector<student> stu;
    for (int i = 0; i < 3; i++)
    {
        cin >> no;
        cin >> score;
        student temp(no,score);
        stu.push_back(temp);
    }
    sort(stu.rbegin(),stu.rend());
}

vector排序需要定义一个自定义的排序函数,

#include <bits/stdc++.h>
using namespace std;
class student
{
public:
    int no;
    int score;
    student(int No=0, int Score=0)
    {
        no = No;
        score = Score;
    }
};

bool compareByscore(student stu1,student stu2)
{
    return stu1.score < stu2.score;
}

int main()
{
    int no;
    int score;
    vector<student> stu;
    for (int i = 0; i < 3; i++)
    {
        cin >> no;
        cin >> score;
        student temp(no,score);
        stu.push_back(temp);
    }
    sort(stu.rbegin(),stu.rend(), compareByscore);

    for (vector<student>::iterator it = stu.begin(); it != stu.end(); it++) {
        cout << "学号:" << it->no  << " 成绩:" << it->score << endl;
    }
    return 0;
}

img

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632