我用C++写了一个学生信息管理系统,包括查找、显示、删除、排序等功能,用到了vector容器和类和txt文件,在排序功能中我想根据学号升序排序,学生信息包括学号、姓名、班级,请问我怎么用sort算法进行排序,请给出例子
时间: 2024-01-17 17:05:14 浏览: 57
好的,根据你的要求,我可以给你一个简单的示例代码,演示如何使用sort算法对学生信息按照学号升序排序:
```cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
// 定义学生类
class Student {
public:
string id; // 学号
string name; // 姓名
string cls; // 班级
Student(string id, string name, string cls) {
this->id = id;
this->name = name;
this->cls = cls;
}
};
// 定义比较函数,用于sort排序
bool cmp(Student& s1, Student& s2) {
return s1.id < s2.id;
}
int main() {
vector<Student> students; // 存储学生信息的vector容器
// 读取文件中的学生信息
ifstream fin("students.txt");
if (!fin) {
cout << "文件读取失败!" << endl;
return -1;
}
string id, name, cls;
while (fin >> id >> name >> cls) {
students.push_back(Student(id, name, cls));
}
fin.close();
// 按照学号升序排序
sort(students.begin(), students.end(), cmp);
// 输出学生信息
for (auto& s : students) {
cout << s.id << " " << s.name << " " << s.cls << endl;
}
return 0;
}
```
在这个示例代码中,我们首先定义了一个Student类,用于存储学生信息。然后,我们使用vector容器存储所有的学生信息,并从文件中读取学生信息。接着,我们使用sort算法对学生信息进行排序,排序的依据是学号升序。最后,我们输出排序后的学生信息。
注意,我们使用了一个cmp函数作为sort排序的比较函数,这个函数的作用是告诉sort算法按照什么方式进行排序。在这个例子中,cmp函数比较的是两个学生的学号,如果第一个学生的学号小于第二个学生的学号,那么返回true,否则返回false。这个cmp函数可以根据实际情况进行修改,比如你可以按照姓名进行排序,或者按照班级进行排序。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)