C++之string、vector、deque容器综合案例

string、vector、deque容器综合案例

1、案例描述

有5名选手:选手ABCDE,10个评委分别对每一名选手打分,去除最高分,去除评委中最低分,取平均分。

2、实现步骤

1.创建五名选手,放到vector中
2.遍历vector容器,取出来每一个选手,执行for循环,可以把10个评分打分存到deque容器中
3.sort算法对deque容器中分数排序,去除最高和最低分
4.deque容器遍历一遍,累加总分
5.获取平均分赋值给学生

3、自己的尝试

#include
#include
#include
#include
#include

using namespace std;
class player {
public:
	string name;
	dequescore[10];
	player(string name) {
		this->name = name;
	}

	void dafen(deque& score) {
		for (deque::iterator it = score.begin(); it != score.end(); it++) {
			this->score->push_back(*it);
		}
	}

	void avg() {
		sort(score->begin(), score->end());
		int sum = 0;
		for (deque::iterator it = score->begin() + 1; it != score->end() - 1; it++) {
			sum += *it;
		}
		cout << "他的最终成绩为:" << sum / 8.0 << endl;
	}

	string namee() {
		return this->name;
	}
};

int main() {
	vector H;
	deque S;

	player player1("李斯");
	cout << "该选手的名字为:" << player1.namee() << endl;

	cout << "请打分: " << endl;
	for (int i = 0; i < 10; i++) {
		int sc;
		cin >> sc;
		S.push_back(sc);
	}

	player1.dafen(S);

	cout << "打分结束" << endl;
	player1.avg();
}

4、教学案例

#include
#include
#include
#include
#include
#include 
#include 

using namespace std;
class player {
public:
	player(string name, int score) {
		this->name = name;
		this->m_score = score;
	}
	string name;//姓名
	int m_score;//平均分

};

void createPerson(vector& v) {
	string nameseed = "ABCDE";
	for (int i = 0; i < 5; i++) {
		string name = "选手";
		name += nameseed[i];
		int score = 0;

		player p(name, score);

		//将创建的对象放入容器
		v.push_back(p);

	}
}

void setscore(vector& v)
{
    for (vector::iterator it = v.begin(); it != v.end(); it++) {
        deque d;
        for (int i = 0; i < 10; i++) {
            int score = rand() % 41 + 60; // 生成60~100之间的随机数
            d.push_back(score);
        }

       /* cout << "选手:" << it->name << "的打分:" << endl;
        for (int i = 0; i < d.size(); i++)
        {
            cout << d[i] << " ";
        }
        cout << endl;*/

        sort(d.begin(), d.end());

        d.pop_back();
        d.pop_front();

        int sum = 0;
        for (deque::iterator dit = d.begin(); dit != d.end(); dit++) {
            sum += *dit;
        }
        int avg = sum / d.size();
        it->m_score = avg ; // 假设 Player 类中有一个用于设置分数的成员函数 setScore()
    }
}

void showplayer(vector& v) {
    for (vector::iterator it = v.begin(); it != v.end(); it++)
    {
        cout << "选手姓名:" << (*it).name << " " << "选手得分:" << (*it).m_score << endl;
    }
}

int main() {
	srand((unsigned)time(NULL)); //实现真的随机的种子

	vector v;//选手容器
	createPerson(v);//创建5名选手
	
	setscore(v);//打分

    showplayer(v);//显示选手信息
}

你可能感兴趣的:(C++,c++,rpc,开发语言)