[英]Why does std::priority_queue use max heap instead of min heap?
I always wondered why STL priority queue uses max heap instead of min heap by default.我一直想知道为什么 STL 优先级队列默认使用最大堆而不是最小堆。 Two obvious use cases that come to mind is pathfinding (Dijkstra) and building Huffman codes.
我想到的两个明显用例是寻路 (Dijkstra) 和构建霍夫曼代码。 Both algorithms need to pull min elements first.
两种算法都需要先拉取最小元素。 Since sorting (std::sort) uses ascending order by default, I wonder what was the design reasoning behind priority_queue, because I would very much prefer a min heap by default.
由于排序 (std::sort) 默认使用升序,我想知道 priority_queue 背后的设计原因是什么,因为我更喜欢默认情况下的最小堆。
Priority_queue is adapted from make_heap/pop_heap/push_heap/sort_heap. Priority_queue 改编自 make_heap/pop_heap/push_heap/sort_heap。 When you make_heap with less, the elements are sorted ascending.
当您使用 less 进行 make_heap 时,元素按升序排列。 And the last element is treated as root element.
最后一个元素被视为根元素。 So it is max heap.
所以它是最大堆。 I guess there are two reasons:
我想有两个原因:
There is a reason, but it is to do with the interconnected features of C++.这是有原因的,但这与 C++ 的互连特性有关。
priority_queue
was designed to be an easy-to-use wrapper around make_heap
, pop_heap
and push_heap
. priority_queue
被设计为一个易于使用的封装make_heap
、 pop_heap
和push_heap
。 It makes sense for the heap functions to keep the largest value at the front, because that is what you need to be able to implement sort_heap
, which also use the heap functions.堆函数将最大值保留在前面是有意义的,因为这是您能够实现
sort_heap
,它也使用堆函数。
Of course, you can always instantiate priority_queue
with greater
rather than less
to get the behaviour you want.当然,您始终可以使用
greater
而不是less
来实例化priority_queue
以获得您想要的行为。
In the English language, something with a larger priority should happen first.在英语中,优先级更高的事情应该先发生。 Therefore, in a priority queue, something with a higher priority should be popped first.
因此,在优先级队列中,优先级高的东西应该先被弹出。
Basically the answer to your question is because the definition of the word priority strongly implies ordering from largest to smallest.基本上你的问题的答案是因为优先级这个词的定义强烈暗示从大到小排序。
Just imagine a priority queue like a hospital lobby.想象一下像医院大厅这样的优先队列。 Patients with the largest priority (urgent cases) should be a the front of the queue for treatment.
优先级最高的患者(紧急情况)应该排在治疗队列的最前面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.