在C++中创建一个学生类,学生类中包括学生的姓名,学号,成绩,使用list容器存放至少10个学生信息,调用list容器的sort函数,实现将学生的姓名首字母按字母表从小到大的顺序进行排序,并输出排序后的结果
时间: 2024-04-09 07:28:45 浏览: 99
好的,下面是一个示例代码,演示如何在C++中创建一个学生类,并使用list容器存放学生信息并按照姓名首字母进行排序:
```cpp
#include <iostream>
#include <list>
#include <string>
#include <algorithm>
class Student {
public:
std::string name;
int studentId;
float score;
Student(const std::string& name, int studentId, float score)
: name(name), studentId(studentId), score(score) {}
};
// 自定义比较函数,用于按照姓名首字母进行排序
bool compareByName(const Student& s1, const Student& s2) {
return s1.name < s2.name;
}
int main() {
std::list<Student> students;
students.push_back(Student("Alice", 101, 85.5));
students.push_back(Student("Bob", 102, 78.2));
students.push_back(Student("Charlie", 103, 92.3));
students.push_back(Student("David", 104, 79.8));
students.push_back(Student("Eva", 105, 88.6));
students.push_back(Student("Frank", 106, 91.7));
students.push_back(Student("Grace", 107, 83.9));
students.push_back(Student("Hank", 108, 76.4));
students.push_back(Student("Ivy", 109, 84.2));
students.push_back(Student("Jack", 110, 89.1));
// 使用自定义的比较函数进行排序
students.sort(compareByName);
// 输出排序后的结果
for (const Student& student : students) {
std::cout << "Name: " << student.name << ", Student ID: " << student.studentId << ", Score: " << student.score << std::endl;
}
return 0;
}
```
这段代码定义了一个`Student`类,包含学生的姓名、学号和成绩。然后,在`main`函数中创建一个`std::list<Student>`容器,存放10个学生对象。接着,使用自定义的比较函数`compareByName`作为参数调用`sort`函数,实现将学生的姓名按照字母表顺序进行排序。最后,使用循环遍历容器并逐个输出排序后的学生信息。
希望这个示例对你有帮助!如果有任何疑问,请随时提出。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)