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

本文介绍了STL中通过priority_queue实现的最大堆(max-heap)和最小堆(min-heap),讲解了相关成员函数,并通过示例进行说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值