编写c++程序,利用链表list容器来容纳学生Student类对象,并采用函数对象实现学生对象的按序号排序,然后输出学生信息。
时间: 2024-05-06 22:14:53 浏览: 17
以下是一个简单的示例代码:
```c++
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
class Student {
public:
int id;
string name;
int age;
Student(int i, string n, int a) : id(i), name(n), age(a) {}
void display() {
cout << "ID: " << id << ", Name: " << name << ", Age: " << age << endl;
}
};
class Compare {
public:
bool operator()(const Student& s1, const Student& s2) {
return s1.id < s2.id;
}
};
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(Compare());
for (auto it = students.begin(); it != students.end(); ++it) {
it->display();
}
return 0;
}
```
这个程序定义了一个 `Student` 类,包含学生的 ID、姓名和年龄三个属性,以及一个 `display()` 函数用于输出学生信息。程序还定义了一个 `Compare` 函数对象,用于按学生 ID 对学生进行排序。然后,程序创建了一个 `list` 容器来存储学生对象,向容器中添加了三个学生信息,最后使用 `sort()` 函数和 `Compare` 函数对象对学生进行排序,并输出学生信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)