STL——priority_queue模拟

#pragma once
#include<vector>
#include<iostream>
namespace crx {
	using std::vector;
	using std::cout;
	using std::cin;
	using std::endl;
	//仿函数
	template<class T>
	struct less {
		bool operator()(const T& a,const T& b) {
			return a < b;
		}
	};
	template<class T>
	struct greater {
		bool operator()(const T& a, const T& b) {
			return a > b;
		}
	};
	template<class T,class Container = vector<T>,class Compare = less<T>>
	class priority_queue {
		//默认是大堆,大的往上走
	public:
		void Swap(T& a,T& b) {
			T p = a;
			a = b;
			b = p;
		}
		//向上调整算法
		void AdjustUp(int child) {
			int parent = (child - 1) / 2;
			Compare com;
			while (child > 0) {
				//_con[child]>_con[parent]
				if (com(_con[parent],_con[child])) {
					Swap(_con[child], _con[parent]);
					child = parent;
					parent = (child - 1) / 2;
				}
				else {
					break;
				}			
			}
		}
		//向下调整算法
		void AdjustDown(int root) {
			int parent = root;
			int child = parent * 2 + 1;
			Compare com;
			while (child < _con.size()) {
				if (child + 1 < _con.size() && _con[child + 1] > _con[child]) {
					child++;
				}
				//_con[parent] < _con[child]
				if (com(_con[parent] , _con[child])) {
					Swap(_con[parent], _con[child]);
					parent = child;
					child = 2 * parent + 1;
				}
				else {
					break;
				}
			}
		}
		void push(const T& x)
		{
			_con.push_back(x);
			AdjustUp(_con.size() - 1);
		}

		void pop()
		{
			Swap(_con[0], _con[_con.size() - 1]);
			_con.pop_back();
			AdjustDown(0);
		}
		T& top()
		{
			return _con[0];
		}
		size_t size()const
		{
			return _con.size();
		}

		bool empty()const
		{
			return _con.empty();
		}

		
	private:
		Container _con;
	};
	void test_priority_queue() {
		priority_queue<int> pq;
		pq.push(3);
		pq.push(1);
		pq.push(9);
		pq.push(4);
		pq.push(2);
		while (!pq.empty()) {
			cout << pq.top() << " ";
			pq.pop();
		}
		cout << endl;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值