使用lambda表达式可灵活自定义std::sort排序规则,支持基本类型升序、结构体多条件排序及捕获外部变量实现动态排序,提升代码简洁性与可读性。

在C++中,可以使用lambda表达式作为排序的比较函数,结合std::sort对std::vector进行灵活排序。这种方式简洁、直观,特别适合自定义排序规则。
基本语法:使用lambda排序vector
lambda表达式的语法结构为:[capture](parameters) -> return_type { function_body }
在排序中,通常只需要参数和函数体部分,返回布尔值表示是否需要交换顺序。
示例:对整数vector按升序排序
#include#include #include int main() { std::vector
nums = {5, 2, 8, 1, 9}; std::sort(nums.begin(), nums.end(), [](int a, int b) { return a zuojiankuohaophpcn b; // 升序 }); for (int n : nums) { std::cout zuojiankuohaophpcnzuojiankuohaophpcn n zuojiankuohaophpcnzuojiankuohaophpcn " "; } // 输出: 1 2 5 8 9}
按自定义类型排序(如结构体)
当vector中存储的是结构体或类对象时,lambda能清晰定义排序逻辑。
立即学习“C++免费学习笔记(深入)”;
示例:按学生分数降序排序,分数相同时按名字升序
struct Student {
std::string name;
int score;
};
std::vector students = {
{"Alice", 85},
{"Bob", 90},
{"Charlie", 85}
};
std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
if (a.score == b.score) {
return a.name < b.name;
}
return a.score > b.score; // 分数高的在前
});
捕获外部变量动态排序
lambda可以捕获外部变量,实现运行时决定排序方式。
示例:根据用户选择的字段排序
std::string sortBy = "name"; // 可动态改变std::sort(students.begin(), students.end(), [sortBy](const Student& a, const Student& b) { if (sortBy == "name") { return a.name < b.name; } else { return a.score > b.score; } });
注意:若需修改捕获的变量,应使用mutable关键字,但排序中一般不需要。
基本上就这些。lambda配合std::sort让C++的排序既高效又可读。











