【STL实例】deque容器、vector容器 评委打分案例

mac2024-11-03  11

评委打分案例

创建五个选手(姓名、得分),10个评委对五个选手进行打分 得分规则:去除最高分,去除最低分,取出平均分 按得分对25名选手进行排名

#include<iostream> #include<deque> #include<string> #include<vector> #include<algorithm> using namespace std; /*评委打分案例(sort算法排序) 创建五个选手(姓名、得分),10个评委对五个选手进行打分 得分规则:去除最高分,去除最低分,取出平均分 按得分对25名选手进行排名 */ //选手类 class player { public: player() {}; player(string name,int score):mName(name),mScore(score){} public: string mName; int mScore; }; void create_player(vector<player>&v) { string nameSeed = "abcdefghijklmnopqrstuvwxy"; for (int i = 0; i < 25; i++) { player p; p.mName = "选手"; p.mName = nameSeed[i]; p.mScore = 0; v.push_back(p); } } void PrintScore(int val) { cout << val <<" "<< endl; } //打分 void Set_Score(vector<player>& v) { for (vector<player>::iterator it = v.begin(); it != v.end(); ++it) { //当前学生进行打分 deque<int>dScore; for (int i = 0; i < 10; ++i) { int score = rand() % 41 + 60; dScore.push_back(score); } //对分数进行排序 sort(dScore.begin(), dScore.end()); //for_each(dScore.begin(), dScore.end(),PrintScore); //cout << endl; //去除最高分,去除最低分 dScore.pop_front(); dScore.pop_back(); //求平均分 int sum = 0; for (deque<int>::iterator dit = dScore.begin(); dit != dScore.end(); ++dit) { sum += (*dit); } int avsum = sum / dScore.size(); (*it).mScore = avsum; } } //排序规则 bool mycompare(player& p1, player& p2) { return p1.mScore > p2.mScore; } //根据选手分数排序 sort默认从小到大 希望从大到小 void print_Rank(vector<player>& v) { //排序 sort(v.begin(), v.end(), mycompare); //打印 for (vector<player>::iterator ddit = v.begin(); ddit != v.end(); ++ddit) { cout << "姓名:选手" << (*ddit).mName << " 分数:" << (*ddit).mScore << endl; } } int main(void ) { //定义vector容器,保存选手信息 vector<player>vplist; create_player(vplist); Set_Score(vplist); print_Rank(vplist); return 0; }

输出:

最新回复(0)