最大堆(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;
}
成员函数有:
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;
}
相关文章推荐
- 最大流/最小割(maxflow/mincut)的原理讲解和代码实现
- Collection.max min最大最小值 集合(list set map)
- Stack with max and min 查找堆中最大最小数
- Max-Min-搜索int类型数字文件中的最大数和最小数写到屏幕
- min-height,max-height(最大最小宽度高度)支持ie6
- js取最小最大值--Math.min()、math.max()
- Java实现用最大堆和最小堆查找中位数 Find median with min heap and max heap in Java
- 最大最小公平共享算法 Max-min Fair Share Algorithm
- CSS中最大宽度属性max-width和最小宽度属性min-width
- maxflow mincut 最大流最小割
- STL_算法_最小值和最大值(min_element、max_element)
- CSS3 最小内容尺寸(min-content size)和最大内容尺寸(max-content size)简介
- C++ *max_element函数找最大元素 *min_element函数找最小元素 STL算法
- Google 面试题:Java实现用最大堆和最小堆查找中位数 Find median with min heap and max heap in Java
- C++ *max_element函数找最大元素 *min_element函数找最小元素 STL算法
- CV | Max Flow / Min Cut 最大流最小割算法学习
- 实验九指针1、程序填空:下列程序在数组中同时查找最大元素和最小元素的下标,分别存放在 main()函数的max 和 min 变量中。要求:根据运行结果分析程序和填空,并注释说明填充依据。
- 最大公约数 和最小公倍数。(max Common Divisor min common multiple)
- matlab实现图割算法中的最大流最小割Max-flow/min-cut问题(一)
- 实验9 指针1 、程序填空:下列程序在数组中同时查找最大元素和最小元素的下标,分别存放在 main()函数的max 和 min 变量中。要求:根据运行结果分析程序和填空,并注释说明填充依