目的:
定义5个学生,包含名字和分数,对成员进行从大到小排序,并输出
#include <iostream>
#include <cstring>
#include <vector>
#include <random>
#include <ctime>
#include <algorithm>
using namespace std;
//定义Student类,设置名字和分数属性
class Student{
public:
Student(int score,string name){
this->name = name;
this->score = score;
}
public:
int score;
string name;
};
//设置类成员
void SetStudent(vector<Student> &s){
string name[] ={"aa","bb","cc","dd","ee"};
Student a(,"");
srand(time());
for(int i =;i<;i++){
a.name = name[i];
a.score = +random()%;
s.push_back(a);
}
}
//定义针对Student类的排序规则函数
bool My_count(Student &v1,Student &v2){
return v1.score>v2.score;
}
//设置分数,对分数进行排名
void SetScore(vector<Student> &s){
sort(s.begin(),s.end(),My_count);//sort()支持随机存储容器,传入规则时,不带()
}
//利用迭代器对成员进行输出
void CoutScore(vector<Student> &s){
for(vector<Student>::iterator it = s.begin();it != s.end();it++){
cout <<"Student :"<<(*it).name <<" "<<"Score :"<<(*it).score<<endl;
}
} int main() {
vector<Student> s;
SetStudent(s);
SetScore(s);
CoutScore(s);
return ;
}