CPP - sort

时间:2023-03-08 21:39:13
CPP - sort
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class student{
public:
student(){}
student(int num, string str, int s) {id= num;name = str;score = s; }
student(student &stu){id = stu.id;name = stu.name;score = stu.score;}
int getid(){ return id; }
string getname(){ return name; }
int getscore(){ return score; }
bool operator < (const student &stu)const { return score < stu.score; }
bool operator > (const student &stu){ return score > stu.score; }
bool operator () (const student &stu1, const student &stu2){ return stu1.score > stu2.score; }
private:
int id;
string name;
int score;
}; int cmp( const void *a ,const void *b)
{
return ((student *)a)->getscore() - ((student *)b)->getscore() ;
} int main() {
int i;
student stu[5] = { student(1, "zhu", 86),student(2, "xing", 92),
student(3, "zhao", 78),student(4, "fu", 88),student(5, "liu", 76) };
qsort(stu,5,sizeof(stu[0]),cmp);
for(i=0;i<5;i++)
cout << stu[i].getid() <<" "<< stu[i].getname()<<" " << stu[i].getscore() << endl;
return 0;
}