案例描述 有5名选手:选手ABCDE,10个评委分别对每一名选手打分,去除最高分,去除评委中最低分,取平均分。
黑马的实现步骤
1. 创建五名选手,放到vector中
2. 遍历vector容器,取出来每一个选手,执行for循环,可以把10个评分打分存到deque容器中
3. sort算法对deque容器中分数排序,去除最高和最低分
4. deque容器遍历一遍,累加总分
5. 获取平均分
我大致是按照黑马的步骤实现的,但我的评委打分的容器是放在每个选手的成员参数内的,可以相互关联。
代码如下:
#include<iostream>
using namespace std;
#include<vector>
#include<deque>
#include<algorithm>
//评委打分
class Person
{
public:
Person() {}
Person(string name, int score)
{
m_name = name;
m_score = score;
}
/*void getScore()
{
for (int i = 0; i < 10; i++)
{
int score;
cin >> score;
d.push_back(score);
}
}*/
//分数容器
deque<int> d;
string m_name;
int m_score;
};
void creatPerson(vector<Person>& v)
{
string nameSeed = "ABCDE";
for (int i = 0; i < 5; i++)
{
//string name = "选手";
//name += nameSeed[i];
string name;
name += nameSeed[i];
int score = 0;
Person p(name, score);
//放入vector容器中
v.push_back(p);
}
}
void setScore(vector<Person>& v)
{
//遍历容器
for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
{
//第一层遍历的是Person
//
//输入分数
for (int i = 0; i < 10; i++)
{
int score = rand() % 41 + 60; // 60 ~ 100
(*it).d.push_back(score);
}
//排序
sort(it->d.begin(), it->d.end());
//删除最高分和最低分
(*it).d.pop_back();
(*it).d.pop_front();
//记总分
int score = 0;
for (deque<int>::iterator dit = (*it).d.begin(); dit != (*it).d.end(); dit++)
{
score += (*dit);
}
//导入person内
it->m_score = score / (*it).d.size();
}
}
void showScore(vector<Person> v)
{
//cout << "选手编号:" << v.m_name << " " << "分数" << p.m_score << endl;
for (vector<Person>::const_iterator it = v.begin(); it != v.end(); it++)
{
//是person
cout << "选手编号:" << (*it).m_name << " " << "分数:" << (*it).m_score << endl;
//展示所有分数
for (deque<int>::const_iterator dit = (*it).d.begin(); dit != (*it).d.end(); dit++)
{
//是deque
cout << (*dit) << " ";
}
cout << endl;
cout << endl;
}
}
int main()
{
vector<Person> v;
creatPerson(v);
setScore(v);
showScore(v);
system("pause");
return 0;
}