简体   繁体   English

使用STL优先队列的最小堆说明

[英]Min Heap using STL Priority Queue explanation

I am fairly new to C++ and I was trying to implement a Min Heap using Priority Queue STL in C++. 我对C ++相当陌生,我试图使用C ++中的Priority Queue STL实现Min Heap。 I looked around the web and chanced upon a code, the link to which I have added at the bottom. 我环顾四周,偶然发现了一个代码,该代码是我在底部添加的链接。

I understand how vectors work and I also understand what a functor is but I can't understand how 'return i>j' plays a part in arranging the elements from minimum to maximum. 我了解向量的工作原理,也了解函子是什么,但我无法理解“ return i> j”如何将元素从最小排列到最大。

I will post the code here. 我将在此处发布代码。

#include <queue>
#include <iostream>

using namespace std;

struct comparator {
     bool operator()(int i, int j) {
     return i > j;
    }
};

int main(int argc, char const *argv[])
{
     priority_queue<int, std::vector<int>, comparator> minHeap;

    minHeap.push(10);
    minHeap.push(5);
    minHeap.push(12);
    minHeap.push(3);
    minHeap.push(3);
    minHeap.push(4);

    while (!minHeap.empty()) {
    cout << minHeap.top() << " ";
    minHeap.pop();
    }
    return 0;
}

Could someone please trace the program's execution? 有人可以跟踪程序的执行情况吗? I have been trying to understand how this program works for the past couple of hours with no luck. 我一直在尝试了解该程序在过去的几个小时中是如何运作的,但是没有运气。

I got the code from here 我从这里得到代码

Priority queues first element is always the greatest of the elements it contains, according to a given criterion. 根据给定的标准,优先级队列中的第一个元素始终是它包含的最大元素。 This criterion is your functor comparator . 此标准是您的函子comparator In this case, it's defining that for a two given elements the minor one should be first. 在这种情况下,它定义了对于两个给定元素,次要元素应该是第一个。

Hence, in your code, if we extract all the elements the output will be the element ordered min to max: 因此,在您的代码中,如果我们提取所有元素,则输出将是从最小到最大排序的元素:

while (!minHeap.empty()) {
   cout << minHeap.top() << " ";
   minHeap.pop();
}
//output: 3,3,4,5,10,12

The algorithm to push an element is like a heap: 推入元素的算法就像堆:

  1. Place the new element in the next available position in the array. 将新元素放置在数组中的下一个可用位置。 (lower level of the tree) (树的下层)
  2. Compare the new element with its parent using the functor provided ( comparator ). 使用提供的函子( comparator )将新元素与其父元素进行comparator In this case, you comparison is "if the new element is smaller", then swap it with its parent. 在这种情况下,您的比较是“如果新元素较小”,则将其与其父元素交换。
  3. Continue this process until either: 继续此过程,直到:
    • the new element's parent is smaller than or equal to the new element, or 新元素的父元素小于或等于新元素,或者
    • the new element reaches the root (index 0 of the array) 新元素到达根(数组的索引0)

Maybe it is more clear to see how the algorithm works with a visual example: Imagine you have already pushed the numbers 6,3,5,9 and now you push 2. 也许更直观地看到算法是如何工作的:假设您已经将数字6,3,5,9推入了,现在您推了2。 在此处输入图片说明

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

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