黑马c++ STL部分 笔记(4) 案例-评委打分
--案例描述:
有5名选手:选手ABCDE,10个评委分别对每一名选手打分,去除最高分,去除评委中最低分,取平均分。
--实现步骤:
创建五名选手,放到vector中
遍历vector容器,取出来每一个选手,执行for循环,可以把10个评分打分存到deque容器中
sort算法对deque容器中分数排序,去除最高和最低分
deque容器遍历一遍,累加总分
获取平均分
// 案例-评委打分
/*
案例描述
有五名选手,选手ABCDE,10个评委分别对每一个选手打分,去除最高分和最低分,取平均分。
实现步骤
创建五名选手,放到vector中
遍历vector容器,取出来每一个选手,执行for循环,可以把10个评分打分存到deque容器中
sort算法对deque容器中分数排序,去除最高分和最低分
deque容器遍历一遍,累加总分
获取平均分
*/
#include <bits/stdc++.h>
using namespace std;
class person
{
public:
person(string name, double score)
{
this->name = name;
this->score = score;
}
string name; // 姓名
double score; // 平均分
};
void createperson(vector<person> &v)
{ // 要用&,否则传不到实参中
string nameseed = "ABCDE";
for (int i = 0; i < 5; i++)
{
string name = "选手";
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中
deque<int> d;
for (int i = 0; i < 10; i++)
{
int score = rand() % 41 + 60; // 0+60~40+60=60~100
d.push_back(score);
}
// 显示评委打分
cout << (*it).name << "的打分分别为"
<< " ";
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);
}
double avg = (sum * 1.0) / d.size(); // sum/8
(*it).score = avg;
}
}
int main()
{
// 随机数种子
srand((unsigned int)time(NULL));
// 创建五名选手
vector<person> v; // 存放选手的容器
createperson(v);
// 测试
// for(vector<person>::iterator it=v.begin();it!=v.end();it++){
// cout<<(*it).name<<" "<<(*it).score<<endl;
// }
// 给五名选手打分
setscore(v);
// 显示最后得分
for (vector<person>::iterator it = v.begin(); it != v.end(); it++)
{
cout << (*it).name << " " << (*it).score << endl;
}
}
/*
总结:
*/
原文地址:https://blog.csdn.net/l141930402/article/details/136382433
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!