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, andfalse
otherwise.
人话来讲,比较两个参数,返回 bool
值,当返回 true
时,第一个参数排在第二个参数前面,即第一个参数先进入 Container
(如 vector
)
std::greater
std::less
std::greater
: 当第一个参数大于第二个参数时,返回 true
For T which is not a pointer type,
true
iflhs > rhs
,false
otherwise.
(lhs
为第一个参数,rhs
为第二个参数)
std::less
反之
对于 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()
所以,排序的结果是较大的数在下面,较小的数在上面,即小顶堆
当容器里面不是 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
值较小的排在优先级队列的下方,可以理解为大顶堆