C++:STL学习之vector容器、deque容器使用 案例-评委打分

**来自某不知名的二次元的初学者程序员 就是想放一个图**

案例-评委打分

案件描述

有五名选手:选手ABCDE,10个评委分别对每一名选手进行打分,去除评委中的最高分与最低分,取平均数。

实现思路

1、使用vector容器存放五个选手;
2、遍历vector容器,取出每一名选手,将十名评委的打分存到deque容器中去;
3、使用sort算法对deque容器中的数据进行排序,并去除掉最高分和最低分;
4、遍历deque容器,累加总分并求出平均数;
5、打印五名选手的得分。

代码实现

#include<iostream>
using namespace std;
#include<string>
#include<vector>
#include<deque>
#include<algorithm>

//创建选手类
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 namespeed = "ABCDE";
	for (int i = 0; i < 5; i++)
	{
    
    
		string name = "选手";
		name += namespeed[i];

		int score = 0;
		Person p(name,score);
		//将创建的Person对象放入 vector容器中
		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;
			d.push_back(score);
		}
		//对分数进行排序,同时去掉最高分和最低分
		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;//求得评委分数总和
		}
		int avg = sum / d.size();
		it->m_Score = avg;//将求得的平均分赋值给选手
	}
}

//打印输出五名选手的信息
void printPerson(vector<Person>& v)
{
    
    
	for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
	{
    
    
		cout << "选手姓名为 : " << it->m_Name << "\t选手的综合得分为 : " << it->m_Score << endl;
	}
}

//测试案例
void test01()
{
    
    
    //创建五名选手
	vector<Person>v;//存放选手的vector容器
	CreatePerson(v);
	setscore(v);
	printPerson(v);
}

int main()
{
    
    
	test01();
	
	system("pause");
	return 0;
}

运行结果

总结

在代码实现的过程中,使用不同的容器可巧妙的解决问题。

猜你喜欢

转载自blog.csdn.net/qq_50451945/article/details/109249514