编写一个简单的C++程序,利用链表list容器来容纳学生Student类对象,并采用函数对象实现学生对象的按序号排序。然后输出学生信息
时间: 2024-02-25 08:53:50 浏览: 28
好的,我来为您编写这个程序。以下是C++代码:
```c++
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
class Student {
public:
Student(int num, string name, int age) : num(num), name(name), age(age) {}
void print() const {
cout << "num: " << num << ", name: " << name << ", age: " << age << endl;
}
bool operator<(const Student& other) const {
return num < other.num;
}
private:
int num;
string name;
int age;
};
class StudentSorter {
public:
bool operator()(const Student& s1, const Student& s2) const {
return s1 < s2;
}
};
int main() {
list<Student> students;
students.push_back(Student(3, "Tom", 20));
students.push_back(Student(1, "Alice", 18));
students.push_back(Student(2, "Bob", 19));
students.sort(StudentSorter());
for (const auto& student : students) {
student.print();
}
return 0;
}
```
程序定义了一个 `Student` 类,其中包含学号、姓名和年龄三个成员变量,以及一个 `print()` 成员函数用于输出学生信息。然后定义了一个 `StudentSorter` 函数对象,用于比较学生对象的序号大小。最后在 `main()` 函数中,创建了一个 `list` 容器来存储 `Student` 对象,并且调用了 `sort()` 成员函数来对学生对象按序号排序,并输出排序后的学生信息。
运行程序,输出如下:
```
num: 1, name: Alice, age: 18
num: 2, name: Bob, age: 19
num: 3, name: Tom, age: 20
```