1. 需求
STL容器案例:评委打分
有5名选手:选手ABCDE,10个评委分别对每一名选手打分,去除最高分,去除评委中最低分,取平均分。
2. C++代码实现
#include <algorithm>
#include <iostream>
#include <string>
#include <random>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <deque>
#include <fstream>
using namespace std;
class Candidate {
public:
Candidate(string &name) {
m_name = name;
m_avg = 0;
}
void giveScore(int score) {
m_score.push_back(score);
}
void sortScore() {
sort(m_score.begin(), m_score.end());
}
void throwScore() {
m_score.pop_back();
m_score.pop_front();
}
void avgScore() {
int sum = 0;
for (auto i: m_score) {
sum += i;
}
m_avg = sum / m_score.size();
// cout << "A's size is " << m_score.size() << endl;
}
int getAvg() {
return m_avg;
}
string getName() {
return m_name;
}
private:
deque<int> m_score;
int m_avg;
string m_name;
};
void teacherScore(Candidate &c) {
int score = 0;
for (int i = 0; i < 10; ++i) {
score = 61 + (rand() % 40); // 60~100
c.giveScore(score);
}
}
void createCan(vector<Candidate> &v) {
string nameSeed = "ABCDE";
for (auto i : nameSeed) {
string name;
name += i;
Candidate c(name);
v.push_back(c);
}
}
void test01() {
vector<Candidate> v;
createCan(v);
for (auto candidate: v) {
teacherScore(candidate);
candidate.sortScore();
candidate.throwScore();
candidate.avgScore();
cout << candidate.getName() << "'s avg is " << candidate.getAvg() << endl;
}
}
int main()
{
// STL容器案例:评委打分
// 有5名选手:选手ABCDE,10个评委分别对每一名选手打分,去除最高分,去除评委中最低分,取平均分。
test01();
// system("pause");
return 0;
}
3. 输出
A’s avg is 78
B’s avg is 82
C’s avg is 85
D’s avg is 80
E’s avg is 81

199

被折叠的 条评论
为什么被折叠?



