某人的作业,A档第一题

本文介绍了一个简单的C++程序,用于实现学生分数的输入、排序和输出功能。该程序使用了向量和自定义结构体来存储数据,并通过资源管理类确保了内存的安全释放。
天啊,我又答应帮别人做作业了么。不过同学求助也没什么拒绝的理由……
雷同学你那些作业太长了,少于100行的作业我还能考虑下是不是帮忙做个。我自己也忙啊 T T

Anyway,题目:
[quote]一、 分数统计(10)
要求:(1)输入某班级学生的姓名、分数;
(2)对(1)的分数进行降幂排列并输出;
(3)具有输入输出界面。[/quote]

(初学C++的你们,会心一笑了么?)

不太明白什么叫“具有输入输出界面”。连是CUI还是GUI都不说清楚,不得不说这出题的人真搓。

简短解答:
a.h:
#ifndef A_H
#define A_H

#include <cstring> // for memset() and strcpy()
#include <vector>

#define BUFFER_SIZE 256

struct Student {
char m_name[BUFFER_SIZE];
int m_score;

Student() { memset(m_name, 0, BUFFER_SIZE); }
};

// RAII-style
class ResourceManager {
public:
ResourceManager(std::vector<Student*>* pList) : m_pList(pList) {}

~ResourceManager() {
for (std::vector<Student*>::iterator it = m_pList->begin();
it < m_pList->end();
it++) {
delete *it;
}
}

std::vector<Student*>* getList();

private:
std::vector<Student*>* m_pList;
};

#endif // end A_H


a.cpp:
#include <cstdlib>  // for atoi()
#include <iostream> // for cin, cout and getline()
#include <string>

#include "a.h"

using namespace std;

vector<Student*>* ResourceManager::getList() {
return m_pList;
}

struct LessScore {
bool operator() (Student* first, Student* second) {
return (first->m_score < second->m_score);
}
};

void promptInput(vector<Student *>* list) {
cout << "Enter student information. Press Ctrl+Z and ENTER to end." << endl;
string input;

while (true) {
cout << "Enter name: ";
getline(cin, input);
if (!input.compare("")) return; // end loop on EOF or empty line

Student* s = new Student;
strcpy(s->m_name, input.c_str());

cout << "Enter score: ";
getline(cin, input);
s->m_score = atoi(input.c_str());

list->push_back(s);
}
}

void sortStudentList(vector<Student*>* list) {
sort(list->rbegin(), list->rend(), LessScore());
}

void printStudentList(vector<Student*>* list) {
cout << "Result:" << endl;
for (vector<Student*>::iterator it = list->begin();
it < list->end();
it++) {
cout << "Name: " << (*it)->m_name << ", "
<< "Score: " << (*it)->m_score << endl;
}
}

int main() {
ResourceManager res(new vector<Student*>);

promptInput(res.getList());
sortStudentList(res.getList());
printStudentList(res.getList());
return 0;
}


其实应该对输入的数字做更详细的检查……
也应该对Ctrl+Z(EOF)做[b]真[/b]的检查的……
不过算了,懒

P.S. 我写C++代码果然不行了啊,太久没写了。居然在这么短的代码里也搞得内存泄漏了,太丢脸了 T T
[color=green]// 现在改了,在main()的最后显式析构了那个vector。郁闷嗯。[/color]
<- 不,又改了一遍,这次决定还是用[b]RAII[/b]方式好了。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值