栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ 自定义排序顺序详解,优先级队列 + lambda 表达式

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ 自定义排序顺序详解,优先级队列 + lambda 表达式

1. C++ named requirements ( 具名要求 ) : Compare

C++ 中没有 Comparator 类,Campare 是一个 requirement ,可以理解为一种定义,要求。

yields true if the first argument of the call appears before the second in the strict weak ordering relation induced by this type, and false otherwise.

人话来讲,比较两个参数,返回 bool 值,当返回 true 时,第一个参数排在第二个参数前面,即第一个参数先进入 Container(如 vector )

2. std::greater std::less

std::greater : 当第一个参数大于第二个参数时,返回 true

For T which is not a pointer type, true if lhs > rhs, false otherwise.
( lhs 为第一个参数,rhs 为第二个参数)

std::less 反之

3. 排序

对于 vector 排序时,若使用 std::greater,返回 true 时,第一个参数大于第二个参数,即较大的数排在前面,先进入 vector ,所以排序结果是降序

vector v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };

// sort 默认为升序,即使用 less() 作为参数
sort(v.begin(), v.end(), greater());

对于优先级队列,若使用 std::greater:当第一个参数大于第二个参数时,返回 true,即较大的数排在前面,先进入优先级队列 ,但是 优先级队列 为 先进入的后输出

理解:优先级队列想象为堆,先进入的在下面,后进入的在上面,遍历时使用 top()

所以,排序的结果是较大的数在下面,较小的数在上面,即小顶堆

4. 使用 lambda 表达式自定义顺序

当容器里面不是 int 类型时,就不能直接使用 greater 进行排序

此时可以使用 lambda 表达式,方便地自定义顺序,如:

// lambda 表达式作为 Campare,当返回 true 时,left 先进入,后输出,即在优先级队列(堆)的下方
auto cmp = [](pair left, pair right) -> bool { return left.second < right.second; };
priority_queue, vector>, decltype(cmp)> pq(cmp);

优先级队列里面存放的是 pair,我们定义,当 left.second < right.second 时,返回 true,即 second 值较小的排在优先级队列的下方,可以理解为大顶堆

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/784783.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号