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

标签 c++ comparator priority-queue min-heap max-heap

在 C++ 的 Sort 函数中,第三个可选参数是用于对对象进行排序的比较器。如果我们传入 less 作为比较器,我们将按升序获取对象。 (如果比较器被评估为真,位置不会改变,否则元素将被交换!)我的理解是否正确?

按照同样的方式,如果我们将一个 less 比较器传递给优先级队列,我们​​应该得到一个最小堆,(如果底层数据结构选择为 vector ,则对象按递增顺序排序。如果我们调用 top( ), 会返回vector的第一个元素,也就是最小的数。因此,我认为是min heap) 为什么要得到max heap呢?

最佳答案

根据 this online documentation , C++ 库类 std::priority_queue从比较器在较大元素之前排序较小元素的意义上讲,首先返回最大 元素。从上面的链接:

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. 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.

因此 std::priority_queue<T,std::less<T>>创建最大堆并优先考虑较大的元素。

关于c++ - 排序函数和优先级队列中的比较器 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51178986/

相关文章:

c++ - 更改优先级队列元素是否会导致重新排序队列?

c++ - 如何在valgrind中为进程设置动态链接库路径和环境变量

c++ - 在 C++ 中存储来自文本文件的矩阵

c++ - 使用静态初始化函数

java - 如何制作保留 FIFO 行为的 Java PriorityBlockingQueue?

java - poll() 返回类型与 PriorityBlockingQueue.poll() 冲突

c++ - 在 C++ 程序中调用 Python 函数

android - 无法在android中使用比较器对数据进行排序

java - Java 中的集合排序

java - 什么是可比较的类型转换和 Map.Entry?