C++,STL 029(24.10.13)

内容

一道练习题。

(涉及string,vector,deque,sort)

题目(大致)

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

思路(总体)

(1)创建类Class来记录每个人的姓名和最终成绩(平均分);

(2)用vector容器来装入类Class;

(3)10个评委的打分用deque容器来记录并处理,从而得到最终成绩(平均分)。

代码

cpp 复制代码
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <algorithm>
#include <ctime>

using namespace std;

// 创建类Class来记录每个人的姓名和最终成绩(平均分)
class Person
{
public:
    string m_Name;
    int m_Score; // 最终成绩(平均分)

public:
    Person(string name, int score)
    {
        this->m_Name = name;
        this->m_Score = score;
    }
};

// 用vector容器来装入类Class,并对选手信息进行初步处理
void creatPerson(vector<Person> &v)
{
    string nameSeed = "ABCDE";
    for (int i = 0; i < 5; i++)
    {
        string name = "Player ";
        name += nameSeed[i];

        int score = 0;
        Person p(name, score);

        v.push_back(p);
    }
}

// 10个评委的打分用deque容器来记录并处理,从而得到最终成绩(平均分)
void setScore(vector<Person> &v)
{
    for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
    {
        deque<int> d;
        for (int i = 0; i < 10; i++)
        {
            int score = rand() % 41 + 60; // ???
            d.push_back(score);
        }

        /*
        检测成绩是否已成功录入
        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;
        }

        int avg = sum / d.size(); // 处理成绩总和来得到平均分

        it->m_Score = avg;
    }
}

// 输出结果
void showPerson(vector<Person> &v)
{
    for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
    {
        cout << "姓名:" << it->m_Name << "  最终得分:" << it->m_Score << endl;
    }
}

int main()
{
    srand((unsigned int)time(NULL)); // ???

    vector<Person> v;

    creatPerson(v);
    setScore(v);
    showPerson(v);

    /*
    检测vector容器是否成功已装入 类Class
    for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
    {
        cout << (*it).m_Name << " " << (*it).m_Score << endl;
    }
    */

    return 0;
}

输出结果(不唯一)

其他

关于代码中???的部分,待续。

相关推荐
月光下的麦克6 分钟前
如何查案动态库版本
linux·运维·c++
am心11 分钟前
学习笔记-套餐接口
笔记·学习
小六子成长记23 分钟前
【C++】:搜索二叉树的模拟实现
数据结构·c++·算法
汉克老师26 分钟前
GESP2025年9月认证C++二级真题与解析(编程题1(优美的数字))
c++·算法·整除·枚举算法·求余·拆数
科技林总34 分钟前
【系统分析师】3.6 操作系统
学习
carver w1 小时前
MFC入门教程 最简版
c++·mfc
王老师青少年编程1 小时前
信奥赛C++提高组csp-s之倍增算法
c++·csp·信奥赛·csp-s·提高组·倍增算法·rmq
低频电磁之道1 小时前
编译C++的几种方式(MSVC编译器)
开发语言·c++
Zsy_0510031 小时前
【C++】类和对象(一)
开发语言·c++
是娇娇公主~2 小时前
工厂模式详细讲解
数据库·c++