STL -最大最小堆 priority_queue
阿新 • • 發佈:2017-06-24
常用函數 cnblogs () mes color pre pac clas 常用
//添加頭文件
#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.empty();
heap.push();
heap.pop();
heap.top();
STL -最大最小堆 priority_queue