Enclave_ 2022-06-27 11:22 采纳率: 85.2%
浏览 18
已结题

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());
}

展开全部

  • 写回答

2条回答 默认 最新

  • 关注

    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

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

    或者对student类重载 < 运算符

    #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 operator < (const student& ps)
        {
            return  score < ps.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());
    
        for (vector<student>::iterator it = stu.begin(); it != stu.end(); it++) {
            cout << "学号:" << it->no  << " 成绩:" << it->score << endl;
        }
        return 0;
    }
    

    回复
查看更多回答(1条)
编辑
预览

报告相同问题?

问题事件

  • 系统已结题 7月4日
  • 已采纳回答 6月27日
  • 创建了问题 6月27日
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部