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

在C++中,可以使用lambda表达式作为排序的比较函数,结合std::sort对std::vector进行灵活排序。这种方式简洁、直观,特别适合自定义排序规则。
lambda表达式的语法结构为:[capture](parameters) -> return_type { function_body }
在排序中,通常只需要参数和函数体部分,返回布尔值表示是否需要交换顺序。
示例:对整数vector按升序排序
#include <vector>
#include <algorithm>
#include <iostream>
<p>int main() {
std::vector<int> nums = {5, 2, 8, 1, 9};</p><pre class='brush:php;toolbar:false;'>std::sort(nums.begin(), nums.end(), [](int a, int b) {
return a < b; // 升序
});
for (int n : nums) {
std::cout << n << " ";
}
// 输出: 1 2 5 8 9}
当vector中存储的是结构体或类对象时,lambda能清晰定义排序逻辑。
立即学习“C++免费学习笔记(深入)”;
示例:按学生分数降序排序,分数相同时按名字升序
struct Student {
std::string name;
int score;
};
<p>std::vector<Student> students = {
{"Alice", 85},
{"Bob", 90},
{"Charlie", 85}
};</p><p>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; // 分数高的在前
});</p>lambda可以捕获外部变量,实现运行时决定排序方式。
示例:根据用户选择的字段排序
std::string sortBy = "name"; // 可动态改变
<p>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;
}
});</p>注意:若需修改捕获的变量,应使用mutable关键字,但排序中一般不需要。
基本上就这些。lambda配合std::sort让C++的排序既高效又可读。
以上就是c++++中如何使用lambda排序vector_c++ lambda排序vector实现的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号