lambda表达式配合std::sort可简洁实现自定义排序:1. 基本语法为capture { body },用于升序排序如[](int a, int b) { return a
在C++中,使用lambda表达式进行排序非常方便,尤其配合
std::sort函数时,可以快速定义自定义排序规则。不需要额外写比较函数或仿函数,代码更简洁清晰。1. 基本语法:lambda作为sort的比较函数
lambda表达式的通用格式为:
[capture](parameters) -> return_type { body }
在排序中,通常省略返回类型,由编译器自动推导。例如,对整数数组按升序排列:
#include <algorithm> #include <vector> std::vector<int> nums = {5, 2, 8, 1, 9}; std::sort(nums.begin(), nums.end(), [](int a, int b) { return a </int></vector></algorithm>这里lambda返回
true表示a应排在b前面。2. 按结构体或类成员排序
当需要根据对象的某个字段排序时,lambda能直接访问成员变量。
struct Person { std::string name; int age; }; <p>std::vector<person> people = {{"Alice", 30}, {"Bob", 25}, {"Charlie", 35}};</person></p><div class="aritcle_card flexRow artxards"> <div class="artcardd flexRow"> <a class="aritcle_card_img" rel="nofollow" href="/xiazai/gongju/2823" title="C++14"><img src="https://img.php.cn/upload/manual/001/431/639/6ac8b33c327c4749.png" alt="C++14" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a> <div class="aritcle_card_info flexColumn"> <a rel="nofollow" href="/xiazai/gongju/2823" title="C++14" class="overflowclass">C++14</a> <p class="overflowclass">C++14 对 C++11 的修正与增强版本,适合旧系统维护和较老工具链兼容。</p> </div> <a rel="nofollow" href="/xiazai/gongju/2823" title="C++14" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div><p>// 按年龄升序 std::sort(people.begin(), people.end(), [](const Person& a, const Person& b) { return a.age </p><p>// 按名字字典序降序 std::sort(people.begin(), people.end(), [](const Person& a, const Person& b) { return a.name > b.name; });</p>3. 捕获外部变量实现动态排序
lambda可以捕获局部变量,实现灵活排序策略。
std::string sortBy = "age"; // 可动态改变 <p>std::sort(people.begin(), people.end(), [sortBy](const Person& a, const Person& b) { if (sortBy == "name") { return a.name </p>注意:若捕获的是值类型,无法修改原变量;如需修改,可使用引用捕获
[&],但要确保变量生命周期有效。4. 使用技巧与注意事项
- 参数建议用const引用,避免拷贝大对象:
const T& a, const T& b- 确保比较逻辑满足“严格弱序”:不能有循环依赖,相同元素返回false
- 可结合
std::tie实现多字段排序:std::sort(people.begin(), people.end(), [](const Person& a, const Person& b) { return std::tie(a.age, a.name)这表示先按年龄升序,年龄相同时按名字升序。
基本上就这些。lambda让C++排序更直观高效,掌握好捕获方式和比较逻辑,就能应对大多数场景。不复杂但容易忽略细节,比如别把
写成,否则可能导致未定义行为。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!











