简体   繁体   English

排序函数和优先级队列中的比较器C ++

[英]comparators in sort function and priority queue c++

In C++ Sort function, the third optional parameter is a comparator used to sort the objects. 在C ++ Sort函数中,第三个可选参数是用于对对象进行排序的比较器。 If we pass in less as the comparator, we will get objects in increasing order. 如果我们少传入比较器,则对象将按升序排列。 (if the comparator is evaluated to be true, the positions won't be changed, otherwise elements will be swaped!) Is my understanding correct? (如果比较器评估为真,则位置将不会更改,否则将交换元素!)我的理解正确吗?

Following the same fashion, if we pass a less comparator to priority queue, we should get a min-heap,(if the underlying data structure is chosen to be vector, objects are sorted in increasing order. If we call top(), the first element of vector will be returned, which is the smallest number. Therefore, I think it is a min heap) why do we get a max heap? 按照相同的方式,如果将较少的比较器传递给优先级队列,则应该获得最小堆(如果将基础数据结构选择为向量,则对象将以递增顺序排序。如果调用top(),则将向量的第一个元素将被返回,这是最小的数字。因此,我认为这是一个最小堆)为什么我们得到一个最大堆?

According to this online documentation , the C++ library class std::priority_queue returns the largest element first in the sense that the comparator orders smaller elements before larger elements. 根据此在线文档 ,C ++库类std::priority_queue返回最大的元素,这是因为比较器在较大的元素之前对较小的元素进行了排序。 From above link: 从上面的链接:

Note that the Compare parameter is defined such that it returns true if its first argument comes before its second argument in a weak ordering. 请注意,Compare参数的定义是,如果第一个参数以弱顺序出现在第二个参数之前,则返回true。 But because the priority queue outputs largest elements first, the elements that "come before" are actually output last. 但是由于优先级队列首先输出最大的元素,因此“最后出现”的元素实际上最后输出。 That is, the front of the queue contains the "last" element according to the weak ordering imposed by Compare. 也就是说,根据比较所施加的弱排序,队列的前部包含“最后”元素。

Thus std::priority_queue<T,std::less<T>> makes a max-heap and prioritizes larger elements. 因此, std::priority_queue<T,std::less<T>>产生最大堆并优先处理较大的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM