如何用algorithm 库的sort()函数对结构体进行降序排序
时间: 2025-07-06 21:52:24 浏览: 9
### 使用 C++ `algorithm` 库 `sort()` 函数对结构体进行降序排序
为了使用 C++ 中的 `algorithm` 库中的 `sort()` 函数对结构体数组执行降序排序,可以定义一个比较函数或 lambda 表达式作为第三个参数传递给 `sort()`。该比较器应返回 true 当第一个参数应该排在第二个之前。
#### 定义结构体并实现自定义比较逻辑
假设有一个表示学生的结构体:
```cpp
struct Student {
std::string name;
int score;
bool operator<(const Student& other) const { // 默认升序排列依据分数
return this->score < other.score;
}
};
```
要按照成绩字段对学生记录按降序排序,则可以在调用 `std::sort` 时提供定制化的比较谓词[^1]。
以下是完整的代码示例展示如何完成这一操作:
```cpp
#include <iostream>
#include <vector>
#include <algorithm> // 导入必要的头文件以便访问标准库算法
using namespace std;
// 定义学生类
struct Student {
string name;
int score;
// 提供默认小于运算符用于自然顺序(即升序)
bool operator<(const Student &other) const {
return this->score < other.score;
}
};
int main() {
vector<Student> students = {{"Alice", 87}, {"Bob", 92}, {"Charlie", 75}};
cout << "Before sorting:" << endl;
for (auto s : students) {
cout << s.name << ": " << s.score << endl;
}
// 调用 sort 并传入 Lambda 表达式的逆向版本来进行降序排序
sort(students.begin(), students.end(),
[](const Student &a, const Student &b) -> bool { return a.score > b.score; });
cout << "\nAfter descending order sorting by scores:\n";
for (auto s : students) {
cout << s.name << ": " << s.score << endl;
}
return 0;
}
```
这段程序首先创建了一个包含三个元素的学生列表,并打印原始状态下的这些条目;接着通过指定lambda表达式的方式告诉 `sort()` 如何基于成员变量 `score` 来决定两个对象之间的相对位置——这里选择了大于号 (`>`), 实现了从高到低的成绩排序效果;最后再次遍历已排序后的容器输出结果[^3]。
阅读全文
相关推荐

















