利用链表list容器来容纳学生student类对象,
时间: 2023-06-15 16:08:10 浏览: 103
好的,下面是一个简单的示例代码:
```c++
#include <iostream>
#include <list>
#include <string>
using namespace std;
class Student {
public:
string name;
int age;
Student(string n, int a) : name(n), age(a) {}
};
int main() {
list<Student> students;
students.push_back(Student("Alice", 20));
students.push_back(Student("Bob", 19));
for (auto it = students.begin(); it != students.end(); ++it) {
cout << "Name: " << it->name << ", Age: " << it->age << endl;
}
return 0;
}
```
上面的代码定义了一个 `Student` 类,然后创建了一个 `list<Student>` 容器来存储学生对象。使用 `push_back` 方法将两个学生对象添加到容器中,然后使用迭代器遍历容器并输出学生信息。
相关问题
编写程序,利用链表List容器来容纳学生Student类对象,并采用函数对象实现学生对象的按序号排序,然后输出学生信息
下面是一个利用链表List容器来容纳学生Student类对象,并采用函数对象实现学生对象的按序号排序的示例代码:
```cpp
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
class Student {
public:
Student(int no, const string& name) : no_(no), name_(name) {}
int getNo() const { return no_; }
const string& getName() const { return name_; }
private:
int no_;
string name_;
};
class CompareStudent {
public:
bool operator()(const Student& s1, const Student& s2) const {
return s1.getNo() < s2.getNo();
}
};
int main() {
list<Student> students;
students.push_back(Student(3, "张三"));
students.push_back(Student(2, "李四"));
students.push_back(Student(1, "王五"));
students.sort(CompareStudent());
for (const auto& s : students) {
cout << "学号:" << s.getNo() << ",姓名:" << s.getName() << endl;
}
return 0;
}
```
运行结果如下:
```
学号:1,姓名:王五
学号:2,姓名:李四
学号:3,姓名:张三
```
在上面的代码中,我们定义了一个Student类,它包含学生的学号和姓名;另外,我们还定义了一个CompareStudent函数对象,用于比较两个学生对象的学号大小。在主函数中,我们利用链表List容器来容纳学生Student类对象,然后利用sort算法和CompareStudent函数对象实现了按学号排序。最后,我们遍历链表List容器,输出学生信息。
利用链表list容器来容纳学生student类对象,并采用函数对象实现学生对象的按序号排序,然后输出学生信息
以下是一个示例代码,可以参考:
```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
```