namespace my_priority_queue
{// 仿函数/函数对象template<class T>struct greater{bool operator()(const T& x, const T& y){return x > y;}};template<class T>struct less{bool operator()(const T& x, const T& y){return x < y;}};//为了代码简洁与复用,我们为了满足大堆小堆两种需求,所以需要模板传递仿函数(函数对象);template <class T,class container = vector<T>,class compare = less<T>>//利用模板参数,模糊接收仿函数类,less也可以,greater也可以;class priority_queue{void Adjustup(int child){ int parent = (child - 1) / 2;compare _com;//仿函数对象while (child>0){//此处就是大堆需要用小于的原因,是父节点与子节点比较,如果父节点小于子节点就交换,自然是大堆;if (_com(_con[parent],_con[child])){swap(_con[parent],_con[child]);child = parent;parent = (child - 1) / 2;}else//已经满足一个堆了,退出循环;{break;}}}void AdjustDown(int parent){int child = parent * 2 + 1;compare _com;//仿函数对象while (child<_con.size()){//如果右孩子符合建堆思路(根据需要建大堆还是小堆);if(child+1<_con.size()&&_com(_con[child], _con[child+1])){child = child+1;}if (_com(_con[parent], _con[child])){swap(_con[parent], _con[child]);parent=child;child *= 2; }else {break;}}}public:void push(const T& val){_con.push_back(val);Adjustup(_con.size()-1);//传下标}void pop(){swap(_con[0],_con[_con.size()-1]);_con.pop_back();AdjustDown(0);}size_t size(){return _con.size();}const T& top(){return _con[0];}bool empty(){return _con.empty();}private:container _con;};void test_func1(){//priority_queue<int> pq;priority_queue<int,vector<int>,greater<int>> pq;pq.push(1);pq.push(2);pq.push(3);pq.push(4);pq.push(5);while (!pq.empty()){cout << pq.top() << " ";pq.pop();}}}