功能要求:
利用C++中的STL功能模拟10个评委为5位选手打分的过程。去掉一个最高分,去掉一个最低分,对剩下的数据取平均分即为该选手的最终得分。
本案例中将用随机数模拟评委打分,实际应用中可以修改为输入评委的分数。
代码实现:
自定义数据类型与相关头文件:
#include<iostream>
#include <string>
#include<deque>
#include<vector>
#include<algorithm>
#include<ctime>
using namespace std;class Person
{
public:Person(string name, int score){m_Name = name;m_Score = score;}string m_Name;int m_Score;
};
void createPerson(vector<Person>& v)
{string nameSeed = "ABCDE";for (int i = 0; i < 5; i++){string name = "Competitor:";name += nameSeed[i];Person p(name, 0);v.push_back(p);}
}
自定义功能函数:
void Scoring(vector<Person>& v)
{for (vector<Person>::iterator it = v.begin(); it != v.end(); it++){deque<int> d;for (int i = 0; i < 10; i++){//10个评委int score = rand() % 41 + 60;//60~100随机数d.push_back(score);}cout << it->m_Name << " " << "Scoring:" << endl;for (deque<int>::iterator dit = d.begin(); dit != d.end(); dit++){cout << *dit << " ";}cout << endl;sort(d.begin(), d.end());d.pop_back();//去掉最高分d.pop_front();int sum = 0;for (deque<int>::iterator dit = d.begin(); dit != d.end(); dit++){sum += *dit;}sum /= d.size();it->m_Score = sum;}
}
void Print(vector<Person>& v)
{for (vector<Person>::iterator it = v.begin(); it != v.end(); it++){cout << it->m_Name << " Average:" << it->m_Score << endl;}
}
主函数:
int main()
{srand((unsigned int)time(NULL));//随机数种子vector<Person> v;createPerson(v);Scoring(v);Print(v);return 0;
}