利用链表list容器来容纳学生student类对象,并采用函数对象实现学生对象的按序号排序,然后输出学生信息
时间: 2023-06-15 17:08:09 浏览: 38
以下是一个示例代码,可以参考:
```cpp
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
class Student {
public:
Student(int id, string name, int age) : id_(id), name_(name), age_(age) {}
bool operator<(const Student& another) const {
return id_ < another.id_;
}
friend ostream& operator<<(ostream& os, const Student& student) {
os << "id: " << student.id_ << ", name: " << student.name_ << ", age: " << student.age_;
return os;
}
private:
int id_;
string name_;
int age_;
};
class StudentSorter {
public:
bool operator()(const Student& a, const Student& b) const {
return a < b;
}
};
int main() {
list<Student> students;
students.push_back(Student(3, "Tom", 18));
students.push_back(Student(1, "Alice", 20));
students.push_back(Student(2, "Bob", 19));
students.sort(StudentSorter());
for (const auto& student : students) {
cout << student << endl;
}
return 0;
}
```
输出结果如下:
```
id: 1, name: Alice, age: 20
id: 2, name: Bob, age: 19
id: 3, name: Tom, age: 18
```
相关推荐
![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)