用c++设计一个学生类student,能完成学号姓名成绩的输入并能按成绩对学生排序
时间: 2023-09-07 08:13:20 浏览: 59
以下是基于C++的学生类student,包括学号、姓名和成绩:
```cpp
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class Student {
public:
Student(string id, string name, int score) :
m_id(id), m_name(name), m_score(score) {}
string getID() const { return m_id; }
string getName() const { return m_name; }
int getScore() const { return m_score; }
bool operator<(const Student& s) const { return m_score < s.m_score; }
private:
string m_id;
string m_name;
int m_score;
};
```
在上面的代码中,我们通过构造函数初始化学号、姓名和成绩,并使用 `getID()`、`getName()` 和 `getScore()` 函数获取它们的值。我们还重载了 `<` 运算符来实现按成绩排序。
接下来,我们可以使用 `vector` 存储学生对象并按成绩排序:
```cpp
int main() {
vector<Student> students;
// 输入学生信息
while (true) {
string id, name;
int score;
cout << "请输入学号、姓名和成绩(输入0结束):";
cin >> id;
if (id == "0") break;
cin >> name >> score;
students.emplace_back(id, name, score);
}
// 按成绩排序
sort(students.begin(), students.end());
// 输出学生信息
for (const auto& s : students) {
cout << s.getID() << "\t" << s.getName() << "\t" << s.getScore() << endl;
}
return 0;
}
```
在上面的代码中,我们使用 `vector` 存储学生对象,并在循环中输入学生信息。当输入学号为0时,循环结束。然后我们使用 `sort` 函数按成绩从小到大排序。最后,我们遍历 `vector` 并输出每个学生的信息。
希望这能帮助你。