您的位置:首页 > 其它

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

2013-11-15 14:51 225 查看
在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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  max-heap min-heap
相关文章推荐