当前位置:   article > 正文

C++类对象进行排序_c++类属性排序

c++类属性排序

写在前面

C++类对象按照某一个(或几个)类属性进行排序很早以前就学习过,但是时间久了开始有点忘了,现在就把最常用的一种方法进行以下总结。


一. 问题

现在有一个学生管理系统,用来记录每位同学的姓名、学号、以及成绩。现输入n位同学的信息,然后分别输出成绩最高和最低的学生姓名以及学号。


二. 代码

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
class Student{
    public:
        string name;
        string id;
        int score;
        //类对象排序函数
        friend bool operator <(Student &a,Student &b)
        {
            return a.score!=b.score?a.score<b.score:a.score>b.score;
        } 
};
int main()
{
    int n=0;
    cin>>n;
    Student stu[n];
    string a,b;
    int s=0;
    for(int i=0;i<n;i++)
    {
        cin>>a>>b>>s;
        stu[i].name=a;
        stu[i].id=b;
        stu[i].score=s;
    }
    sort(stu,stu+n);  //执行排序操作
    cout<<stu[n-1].name<<" "<<stu[n-1].id<<endl;
    cout<<stu[0].name<<" "<<stu[0].id;
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

三. 核心点

∙ \bullet 需要在类内部重构函数,声明如下:

friend bool operator <(Student &a,Student &b)

函数内部返回比较格式。

∙ \bullet 在主函数中生成类数组用来存放信息:

Student stu[n];

∙ \bullet 书写排序函数sort:

sort(stu,stu+n);

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/926418
推荐阅读
相关标签
  

闽ICP备14008679号