`
RednaxelaFX
  • 浏览: 3022246 次
  • 性别: Icon_minigender_1
  • 来自: 海外
社区版块
存档分类
最新评论

某人的作业,A档第一题

阅读更多
天啊,我又答应帮别人做作业了么。不过同学求助也没什么拒绝的理由……
雷同学你那些作业太长了,少于100行的作业我还能考虑下是不是帮忙做个。我自己也忙啊 T T

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


(初学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)做的检查的……
不过算了,懒

P.S. 我写C++代码果然不行了啊,太久没写了。居然在这么短的代码里也搞得内存泄漏了,太丢脸了 T T
// 现在改了,在main()的最后显式析构了那个vector。郁闷嗯。
<- 不,又改了一遍,这次决定还是用RAII方式好了。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics