目的:
定義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[5] ={"aa","bb","cc","dd","ee"}; Student a(0,""); srand(time(0)); for(int i =0;i<5;i++){ a.name = name[i]; a.score = 60+random()%40; 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 0; }