STL -最大最小堆 priority_queue

//添加头文件
#include<queue> using namespace std;

最大堆实现:

优先输出大数据
priority_queue<Type, Container, Functional>
Type为数据类型, Container为保存数据的容器,Functional为元素比较方式。
如果不写后两个参数,那么容器默认用的是vector,比较方式默认用operator<,也就是优先队列是大顶堆,队头元素最大。
#include<iostream>  
#include<queue>  
using namespace std;  
  
int main(){  
    priority_queue<int> p;  
    p.push(1);  
    p.push(2);  
    p.push(8);  
    p.push(5);  
    p.push(43);  
    for(int i=0;i<5;i++){  
        cout<<p.top()<<endl;  
        p.pop();  
    }  
    return 0;  
}  

最小堆实现:

    class CMyPair :public CVertex
    {
    public :
        CMyPair(CVertex *a, CVertex *b) {
            m_pair_a = a;
            m_pair_b = b;
            cost = 0;
        }
        ~CMyPair() {};
        double getCost() { return cost; }
        void setCost(double c) { cost = c; }
    protected:
        CVertex * m_pair_a;
        CVertex * m_pair_b;
        double cost;
    };
    struct cmp {
        bool operator()(CMyPair a, CMyPair b) {
            if (a.getCost()== b.getCost())  return a.getCost()>b.getCost();
            return a.getCost()>b.getCost();
        }
    };

priority_queue<CMyPair, vector<CMyPair>,cmp> heap;

常用函数:

入队,如例:heap.push(x); 将x 接到队列的末端。
出队,如例:heap.pop(); 弹出队列的第一个元素,注意,并不会返回被弹出元素的值。
访问队首元素,如例:heap.front(),即最早被压入队列的元素。
访问队尾元素,如例:heap.back(),即最后被压入队列的元素。
判断队列空,如例:heap.empty(),当队列空时,返回true。
访问队列中的元素个数,如例:heap.size()
原文地址:https://www.cnblogs.com/Cherrylalala/p/7072606.html