案例描述
有5名选手:ABCDE,10个评委分别对每一名选手打分,去除最高分和最低分,取平均分;
实现步骤
- 创建五名选手,放到vector中;
- 遍历vector容器,去除每一个选手,执行for循环,把十个评分存到deque容器中;
- sort算法对deque容器中分数排序,去除最高分和最低分;
- 遍历deque容器,累加取平均值;
#include<iostream>
#include<vector>
#include<deque>
#include<string>
#include<algorithm>
using namespace std;
//选手类
class Person
{
public:
Person(string name, double score)
{
m_Name = name;
m_Score = score;
}
string m_Name;
double m_Score;
};
void creatPerson(vector<Person>&v)
{
string nameSeed = "ABCDE";
for(int i = 0; i < 5; i++)
{
string name = "选手";
name += nameSeed[i];//拼接 名称的赋值操作
int score = 0;
Person p(name, score);
//将创建的person对象 放到容器中
v.push_back(p);
}
}
void setScore(vector<Person>&v)
{
for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
{
deque<double>d;
for(int i = 0; i < 10; i++)
{
double score = rand() % 41 + 60;//随机数 60-100(缺点 每次生成数都是一样的)
d.push_back(score);
}
//排序
sort(d.begin(), d.end());
//去除最高分 最低分
d.pop_back();
d.pop_front();
/*****测试代码
//cout << "选手:" << it->m_Name << " 打分:" << endl;
//for (deque<double>::iterator dit = d.begin(); dit != d.end(); dit++)
//{
// cout << *dit << " ";
//}
//cout << endl;
******/
//求平均分
double sum = 0;
for (deque<double>::iterator dit = d.begin(); dit != d.end(); dit++)
{
sum += *dit;
}
it->m_Score = sum / d.size();
}
}
void showScore(const vector<Person>&v)
{
for (vector<Person>::const_iterator it = v.begin(); it != v.end(); it++)
{
cout << it->m_Name << ":" << it->m_Score << endl;
}
}
void test()
{
//创建一个vector容器,存放选手信息
vector<Person>v;
//创建选手实例
creatPerson(v);
/********测试代码
//for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
//{
// cout << (*it).m_Name << " 分数" << (*it).m_Score << endl;
//}
**********/
//获取平均分
setScore(v);
//显示得分
showScore(v);
}
int main()
{
test();
system("pause");
return 0;
}