1.創建堆
a.創建以內置類型(int,float等)為元素的堆.
#include <queue> priority_queue<int> big; // 大頂堆 priority_queue<int, vector<int>, greater<int> > small; // 小頂堆
之后就可以對其使用隊列的操作,比如push和pop.
b.創建以結構體為元素的堆
方法一:
編寫比較函數.
struct node { int val, num, ...; // 自定義一個結構體 }; struct cmp { bool operator()(const node &a, const node &b) { return a.val > b.val; } // 花括號內編寫比較函數 }; priority_queue<node, vector<node>, cmp> q;
這樣就創建了一個以結構體node為元素,以cmp為比較函數的小頂堆,如果想要創建大頂堆,只需要把比較函數中的大於號改為小於號.
除了編寫比較函數外還可以重載運算符,見下面的鏈接.

// 需要考慮到精度問題,以下面為例 // 比較平面上點的坐標大小,比較大小時先比較橫坐標,再比較縱坐標 // 使用了重載運算符方法 struct poi {int x, y;}; const double eps = 1e-8; bool operator <(const poi &a, const poi &b) { return a.x + eps < b.x || a.x < b.x + eps && a.y < b.y; }
方法二(推薦):
重載運算符.
例如,計算最小生成樹時想要按照邊的權大小升序排列,只需要將存邊的結構體定義為:
struct E { int from, to, wei; bool operator<(E &other) const { return wei < other.wei; } };
之后就可以如同內置類型一般對其進行排序,建堆等.這種方法顯然比寫比較函數簡潔的多.
(更多創建結構體堆的方法見https://www.cnblogs.com/flipped/p/5691430.html)