设计一个Student类,包含学生的姓名、学号、成绩等信息。使用vector容器存储多个学生信息,并实现学生信息的输入、输出和排序功能
时间: 2024-04-12 17:28:35 浏览: 37
下面是一个简单的实现,设计了一个Student类,以及使用vector容器存储多个学生信息,并实现了学生信息的输入、输出和排序功能。
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Student {
public:
string name;
int studentID;
int score;
// 构造函数
Student(string name, int studentID, int score) {
this->name = name;
this->studentID = studentID;
this->score = score;
}
};
// 比较函数,用于排序
bool compareStudents(const Student& s1, const Student& s2) {
return s1.score > s2.score; // 按照成绩降序排序
}
int main() {
vector<Student> students;
// 输入学生信息
string name;
int studentID, score;
for (int i = 0; i < 3; i++) {
cout << "请输入第" << i + 1 << "个学生的姓名:";
cin >> name;
cout << "请输入第" << i + 1 << "个学生的学号:";
cin >> studentID;
cout << "请输入第" << i + 1 << "个学生的成绩:";
cin >> score;
Student student(name, studentID, score);
students.push_back(student);
}
// 输出学生信息
cout << "学生信息如下:" << endl;
for (const auto& student : students) {
cout << "姓名:" << student.name << ",学号:" << student.studentID << ",成绩:" << student.score << endl;
}
// 按照成绩排序学生信息
sort(students.begin(), students.end(), compareStudents);
// 输出排序后的学生信息
cout << "按照成绩降序排序后的学生信息如下:" << endl;
for (const auto& student : students) {
cout << "姓名:" << student.name << ",学号:" << student.studentID << ",成绩:" << student.score << endl;
}
return 0;
}
```
这个例子中,我们首先定义了一个Student类,包含了学生的姓名、学号和成绩等信息。然后使用vector容器存储多个学生对象。通过循环输入学生信息,并将每个学生对象添加到vector中。然后使用循环输出所有学生的信息。接下来,我们使用sort函数对学生信息进行排序,通过比较函数compareStudents来指定排序规则。最后,再次循环输出排序后的学生信息。