ある人の宿題、A級の第1題
ああ、また宿題を手伝うと約束したのか.でも同級生が助けを求めても断る理由はないし...
雷さんの宿題は長すぎて、100行未満の宿題はまだ手伝ってくれるかどうか考えられます.自分も忙しいよT T
Anyway、タイトル:
参照
一、点数統計(10)
要求:(1)あるクラスの学生の名前、点数を入力します;
(2)(1)の点数を降順に並べて出力する.
(3)入出力インタフェースを有する.
△C++を初めて勉強したあなたたちは、笑っていましたか.
「入出力インタフェースあり」とは何かよくわかりません.CUIなのかGUIなのかさえはっきり言えないので、この出題者は本当にこすっていると言わざるを得ない.
簡単な回答:
a.h:
a.cpp:
実は入力した数字をもっと詳しくチェックすべきだったのですが・・・
Ctrl+Z(EOF)にも
本当にチェックしたのは・・・
でももういい、怠け者
P.S.私はC++コードを書くのはやはりだめですね.長い間書いていません.こんな短いコードでメモリが漏れるなんて恥ずかしいT
//今変更しましたが、main()の最後にそのvectorを明示的に解析しました.うっとうしいうん.
<-いいえ、もう一度直しましたが、今回はやはり
RAII方式ができました.
雷さんの宿題は長すぎて、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
//今変更しましたが、main()の最後にそのvectorを明示的に解析しました.うっとうしいうん.
<-いいえ、もう一度直しましたが、今回はやはり
RAII方式ができました.