sort 自定义排序
时间: 2024-01-11 12:20:37 浏览: 33
可以使用sort()函数的第三个参数来自定义排序规则。第三个参数是一个函数,用于比较两个元素的大小。该函数应该返回一个布尔值,指示第一个参数是否小于第二个参数。如果返回true,则第一个参数排在第二个参数之前,否则第二个参数排在第一个参数之前。以下是一个自定义排序的示例:
假设我们有一个存储学生信息的结构体,包括学生的姓名和分数。我们想按照分数从高到低对学生进行排序,如果分数相同,则按照姓名的字典序从小到大排序。
```c++
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Student {
string name;
int score;
};
bool cmp(const Student& a, const Student& b) {
if (a.score != b.score) {
return a.score > b.score;
} else {
return a.name < b.name;
}
}
int main() {
vector<Student> students = {{"Tom", 80}, {"Jerry", 90}, {"Alice", 70}, {"Bob", 90}};
sort(students.begin(), students.end(), cmp);
for (const auto& student : students) {
cout << student.name << " " << student.score << endl;
}
return 0;
}
```
输出结果为:
```
Jerry 90
Bob 90
Tom 80
Alice 70
```