代码如下:
#pragma once
#include <iostream>
#include <vector>
using namespace std;template<typename T>
struct Less
{bool operator()(const T &a, const T &b){return a < b;}
};template<typename T>
struct Greater
{bool operator()(const T &a, const T &b){return a > b;}
};template<typename T, typename Container = vector<T>, typename Compare = Less<T>>
class priorityQueue
{
public:void shiftDown(){int parent = 0;int child = 2 * parent + 1;while (child < con.size()){if (child + 1 < con.size() && cmp(con[child], con[child + 1])){++child;}if (cmp(con[parent], con[child])){swap(con[parent], con[child]);parent = child;child = 2 * parent + 1;}else break;}}void shiftUp(int child){int parent = (child - 1) / 2;while (child > 0){if (cmp(con[parent], con[child])){swap(con[parent], con[child]);child = parent;parent = (child - 1) / 2;}else break;}}void push(const T& val){con.push_back(val);shiftUp(con.size() - 1);}void pop(){swap(con[0], con[con.size() - 1]);con.pop_back();shiftDown();}T & top(){return con.front();}size_t size() const{return con.size();}bool empty() const{return con.empty();}private:Container con;Compare cmp;
};
测试代码如下:
#include <iostream>
#include "PriorityQueue.h";
using namespace std;int main()
{priorityQueue<int>pq;pq.push(13);pq.push(14);pq.push(9);pq.push(23);pq.push(12);pq.push(22);while (!pq.empty()){cout << pq.top() << " ";pq.pop();}cout << endl;priorityQueue<int, vector<int>, greater<int>> pq1;pq1.push(13);pq1.push(14);pq1.push(9);pq1.push(23);pq1.push(12);pq1.push(22);while (!pq1.empty()){cout << pq1.top() << " ";pq1.pop();}cout << endl;class A{public:A(int a = 1):_a(a){}bool operator<(const A& a) const{return _a < a._a;}bool operator > (const A &a) const{return _a > a._a;}int _a;};priorityQueue<A> pq2;pq2.push(A(123));pq2.push(A(14));pq2.push(A(13));pq2.push(A(23));pq2.push(A(88));pq2.push(A(999));while (!pq2.empty()){cout << pq2.top()._a << " ";pq2.pop();}cout << endl;return 0;
}
测试结果: