1 ``` 2 #include<iostream> 3 #include<algorithm> 4 #include<ctime> 5 #include<vector> 6 #include<deque> 7 #include<cstring> 8 #include<cstdlib> 9 using namespace std; 10 11 /*评委打分案例(sort算法排序) 12 创建5个选手(姓名,得分),10个评委对5个选手进行打分 13 得分规则:去除最高分,去除最低分,取出平均分 14 按得对5个选手进行排名*/ 15 16 //选手类 17 class Player{ 18 public: 19 string mName; 20 int mScore; 21 public: 22 Player(){} 23 Player(string name,int score):mName(name),mScore(score){} 24 25 }; 26 27 //创建选手 28 void Create_Player(vector<Player>& v){ 29 string nameSeed="ABCDE"; 30 for(int i=0; i<5; i++ ){ 31 Player p; 32 p.mName="选手"; 33 p.mName+=nameSeed[i]; 34 p.mScore=0; 35 36 v.push_back(p); 37 } 38 } 39 40 void PrintScore(int val){ 41 cout<<val<<" "; 42 } 43 //打分 44 void Set_Score(vector<Player>& v){ 45 for(vector<Player>::iterator it=v.begin(); it!=v.end(); it++ ){ 46 //当前学生进行打分 47 deque<int> dScore; 48 //srand(((unsigned) time(NULL))); 49 for(int i=0; i<10; i++ ){ 50 int score=rand()%41+60;//产生[60,101)之间的数字 51 dScore.push_back(score); 52 } 53 54 //对分数进行排序 55 sort(dScore.begin(),dScore.end()); 56 //for_each(dScore.begin(),dScore.end(),PrintScore); 57 //cout<<endl; 58 59 //去除最高分,去除最低分 60 dScore.pop_front(); 61 dScore.pop_back(); 62 //求平均分 63 int totalScore=0; 64 for(deque<int>::iterator vec=dScore.begin(); vec!=dScore.end(); vec++ ){ 65 totalScore+=(*vec); 66 } 67 68 int avgScore=totalScore/dScore.size(); 69 //保存分数 70 (*it).mScore=avgScore; 71 } 72 } 73 74 //排名规则 75 bool mycompare(Player& p1,Player& p2){ 76 return p1.mScore>p2.mScore;//从大到小排序 77 } 78 //根据选手分数排名,sort默认从小到大,希望从大到小 79 void Print_Rank(vector<Player>& v){ 80 //排序 81 sort(v.begin(),v.end(),mycompare); 82 //打印 83 for(vector<Player>::iterator it=v.begin(); it!=v.end(); it++ ){ 84 cout<<"姓名:"<<(*it).mName<<" 得分:"<<(*it).mScore<<endl; 85 } 86 } 87 88 int main(){ 89 90 //定义vector容器,保存选手信息 91 vector<Player> vPlist; 92 Create_Player(vPlist); 93 Set_Score(vPlist); 94 Print_Rank(vPlist); 95 96 return 0; 97 } 98 99 100 ```
原文地址:https://www.cnblogs.com/Bravewtz/p/10325827.html
时间: 2024-10-26 21:51:36