cplus自定义类的排序例子
时间: 2024-01-25 21:04:25 浏览: 31
好的,以下是一个使用C++自定义类进行排序的例子:
```c++
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class Student {
public:
string name;
int age;
int grade;
// 重载小于运算符,按照成绩从大到小排序
bool operator<(const Student &s) const {
return grade > s.grade;
}
};
int main() {
vector<Student> students;
// 添加学生信息
students.push_back({"Tom", 18, 90});
students.push_back({"Bob", 20, 80});
students.push_back({"Alice", 19, 95});
// 按照成绩从大到小排序
sort(students.begin(), students.end());
// 输出排序后的学生信息
for (auto &s : students) {
cout << "姓名:" << s.name << ",年龄:" << s.age << ",成绩:" << s.grade << endl;
}
return 0;
}
```
该例子定义了一个名为Student的类,包含了学生的姓名、年龄和成绩三个属性,并重载了小于运算符,以便在排序时按照成绩从大到小排序。最后在main函数中创建了学生队列students,并添加了三个学生信息。使用sort函数将学生队列按照成绩从大到小排序,并输出排序后的学生信息。
相关推荐
![](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)