C++vector針對排序操作練習


目的:

定義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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM