天天看點

【C++程式設計語言】vector容器和deque容器具體使用案例

#挑戰30天在頭條寫日記#

1.案例描述

有5名選手,選手ABCDE,10個評委分别對每一名選手打分,去除評委的最高和最低分取平均分

2.實作步驟:

  1. 建立五名選手,放到vector容器中
  2. 周遊vector容器,取出來每一個選手,執行for循環,可以把10評分存到deque容器中
  3. sort算法對deque容器中分時排序,去除最高和最低
  4. deque容器周遊一遍,累計總分
  5. 擷取平均分
#include<iostream>
#include <vector>
#include <deque>
#include<algorithm>
using namespace std;

class Person {
public:
    string m_Name;//姓名
    int m_Score;//平均分
    Person(string name, int score) {
        this->m_Name = name;
        this->m_Score = score;
    }
};
//建立五名選手
void createPerson(vector<Person>&v) {

    string nameSeed = "ABCDE";
    for (int i = 0; i < 5; i++) {
        string 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;//取值為60-100
            d.push_back(score);
        }

        cout << "選手:" << it->m_Name << " 打分: " << endl;
        //測試打分
        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 showScore(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));

    //1.建立5名選手
    vector<Person> v;//存放選手容器
    createPerson(v);

    //測試
    //for (vector<Person>::iterator it = v.begin(); it != v.end(); it++) {
        //cout << "姓名: "<< (*it).m_Name << " 分數:"<< (*it).m_Score << endl;
    //}
    
    //2.給5名選手打分
     setScore(v);

    //3.顯示最後得分
     showScore(v);
    system("pause");
    return 0;
}           

繼續閱讀