最大堆(max-heap)和最小堆(min-heap)

来源:互联网 发布:淘宝跟客服聊天 编辑:程序博客网 时间:2024/05/16 18:32

在STL中,二叉堆是通过priority_queue的类模板实现的,标准头文件是<queue>。在STL中实现的是最大堆(max-heap)。

成员函数有:

void push (const Object & x);const Object & top() const;void pop();bool empty();void clear();

优先队列模版用如下参数初始化:项类型,容器类型(几乎总是使用存储项的vector)和比较器。最后两个参数是默认值,并且默认情况下得到最大堆。使用greater函数对象作为比较器可以得到最小堆。

示例:

#include <iostream>#include <vector>#include <queue>#include <functional>#include <string>using namespace std;//Empty the priority queue and print its contents.template <typename PriorityQueue>void dumpContents ( const string & msg, PriorityQueue & pq){      cout << msg << ":" << endl;      while (!pq.empty() )      {             cout << pq.top() << endl;             pq.pop();       }}//Do some inserts and removes (done in dumpContents)int main (){       priority_queue<int> maxPQ;       priority_queue<int, vector<int>, greater<int> > minPQ;       min.PQ.push(4); minPQ.push(3); minPQ.push(5);       max.PQ.push(4); maxPQ.push(3); maxPQ.push(5);               dumpConstents ( "minPQ", minPQ ); // 3 4 5       dumpConstents ( "maxPQ", maxPQ ); // 5 4 3               return 0;}