[code]#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class Student //定义Student类
{
public:
static int allCount;
Student() : mName(""), mID(0), chineseScore(0), mathScore(0) { allCount++; }
Student(const string& name, int id, int cs, int ms) : mName(name), mID(id), chineseScore(cs), mathScore(ms) { allCount++; }
void SetName(const string& name) { mName.assign(name); }
string GetName() const { return mName; }
void SetID(int id) { mID = id; }
int GetID() const { return mID; }
void SetChineseScore(int score) { chineseScore = score; }
int GetChineseScore() const { return chineseScore; }
void SetMathScore(int score) { mathScore = score; }
int GetMathScore() const { return mathScore; }
private:
string mName;
int mID;
int chineseScore;
int mathScore;
};
int Student::allCount = 0;
int main()
{
int n = 0;
printf_s("请输入学生个数:");
cin >> n;
vector<Student> stus;
for (size_t i = 0; i < n; ++i)
{
string name;
int id = 0;
int cs = 0;
int ms = 0;
printf_s("请输入第 %d 个学生的姓名:\t", i + 1);
cin >> name;
printf_s("请输入第 %d 个学生的学号:\t", i + 1);
cin >> id;
printf_s("请输入第 %d 个学生的语文分数:\t", i + 1);
cin >> cs;
printf_s("请输入第 %d 个学生的数学分数: \t", i + 1);
cin >> ms;
stus.emplace_back(Student(name, id, cs, ms));
}
//按语文分数排序
sort(stus.begin(), stus.end(), [](const Student& a, const Student& b) {
return a.GetChineseScore() < b.GetChineseScore();
});
//
int number;
printf_s("请输入需要显示前多少名学生:");
cin >> number;
for (size_t i = 0; i < number; ++i)
{
printf_s(" 姓名: %s\t学号: %04d\t语文: %d\t数学: %d\n",
stus[i].GetName().c_str(), stus[i].GetID(), stus[i].GetChineseScore(), stus[i].GetMathScore());
}
printf_s("程序运行过程中,一共创建了 %d 个 Student 类的对象\n", Student::allCount);
system("pause");
|