编写程序,利用链表list容器来容纳学生student类对象,并采用函数对象实现学生对象的按序号排序,然后输出学生信息
时间: 2023-06-19 08:05:07 浏览: 61
以下是基于链表list容器和函数对象的学生按序号排序程序示例:
```c++
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
// 学生类
class Student {
public:
int id; // 学号
string name; // 姓名
// 构造函数
Student(int id, string name) : id(id), name(name) {}
// 输出学生信息
void print() {
cout << "学号:" << id << ",姓名:" << name << endl;
}
};
// 按学号升序排序的函数对象
class SortById {
public:
bool operator()(const Student& s1, const Student& s2) {
return s1.id < s2.id;
}
};
int main() {
// 创建学生链表
list<Student> students;
students.push_back(Student(1001, "张三"));
students.push_back(Student(1003, "李四"));
students.push_back(Student(1002, "王五"));
// 按学号升序排序
students.sort(SortById());
// 输出学生信息
for (auto it = students.begin(); it != students.end(); ++it) {
it->print();
}
return 0;
}
```
程序运行结果:
```
学号:1001,姓名:张三
学号:1002,姓名:王五
学号:1003,姓名:李四
```