一、案例需求
有5名选手:选手ABCDE
10个评委对每一位选手打分
去掉最低分,最高分,取平均分
二、实现思路
1、创建5名选手 ,放到vector中
2、遍历vector容器,对每一个选手生成10个分数,放到deque容器
3、对deque使用sort函数 ,然后删除队头,队尾
4、遍历deque容器,计算平均数
三、具体代码
#include<iostream>
using namespace std;
#include<vector>
#include<string>
#include<deque>
#include<algorithm>
//@file : judgeMark
//@author : wang
//@date : 2021/4/18 22:24:44
//@brief
class Person
{
public:
Person(string name, int score)
{
this->m_Name = name;
this->m_Score = score;
}
string m_Name;
int m_Score;
};
void CreatePerson(vector<Person>&v)
{
string nameSeed = "ABCDE";
int score = 0;
for (int i = 0; i < 5; i++)
{
string name = "选手";
name += nameSeed[i]; //字符串作为数组
Person p(name, score); //构造函数使用方法
v.push_back(p);
}
遍历vector容器
//for (vector<Person>::iterator it = v.begin();it!=v.end();it++ )
//{
// cout << "姓名:" << it->m_Name << " 分数:" << it->m_Score << endl;
//}
}
void SetScore(vector<Person>& v)
{
//生成随机数
srand((int)time(NULL));
for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
{
//得到10个分数
deque<int>d;
for (int i = 0; i < 10; i++)
{
int score = rand() % 41 + 60; //60~100
d.push_back(score);
}
cout << "\n姓名:" << it->m_Name << " 分数:";
//遍历deque容器
for (deque<int>::iterator dit = d.begin(); dit != d.end(); dit++)
{
cout << (*dit) << " ";
}
//排序后去除最低最高
sort(d.begin(),d.end()); //自带的排序函数!!!
d.pop_front();
d.pop_back();
int sum = 0;
//生成平均数
for (deque<int>::iterator ddit = d.begin(); ddit != d.end(); ddit++) //再次使用dit???
{
sum += *ddit;
}
int avg = sum / d.size();
it->m_Score = avg;
cout << "\n平均分:" << it->m_Score << endl;
}
}
void ShowScore(vector<Person>v)
{
cout << "\n\n\n";
for (vector<Person>::iterator it = v.begin(); it != v.end(); it ++ )
{
cout << "姓名:" << it->m_Name << " 平均分:" << it->m_Score << endl;
}
}
int main()
{
//创建5名选手
vector<Person>v; //不能在函数内部创建容器,这个容器是公用的
CreatePerson(v);
//给选手打分
SetScore(v);
//打印分数
ShowScore(v);
system("pause");
return 0;
}
四、注意事项
1、字符串也可以作为数组使用
string nameSeed = "ABCDE";
for (int i = 0; i < 5; i++)
{
string name = "选手";
name += nameSeed[i]; //字符串作为数组
}
2、构造函数的使用方法
class Person
{
public:
Person(string name, int score)
{
this->m_Name = name;
this->m_Score = score;
}
string m_Name;
int m_Score;
};
Person p(name, score);
v.push_back(p);
3、遍历容器
1)vector容器中存放的是Person类对象,取值使用:it->m_Name
for (vector<Person>::iterator it = v.begin();it!=v.end();it++ )
{
cout << "姓名:" << it->m_Name << " 分数:" << it->m_Score << endl;
}
2)deque中存放的是int, 取值使用:(*dit)
for (deque<int>::iterator dit = d.begin(); dit != d.end(); dit++)
{
cout << (*dit) << " ";
}
4、生成随机数
srand((int)time(NULL));
int score = rand() % 41 + 60; //60~100
5、排序函数
deque<int>d;
for (int i = 0; i < 10; i++)
{
int score = rand() % 41 + 60; //60~100
d.push_back(score);
}
//排序后去除最低最高
sort(d.begin(),d.end()); //自带的排序函数!!!
d.pop_front();
d.pop_back();