优先级队列实现

namespace wh {
	template<class T, class Container = vector<T>, class compare = wh::less<T>>
	class priority_queue {
	public:
		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];
		}

		int size() {
			return _con.size();
		}

		bool empty() {
			return _con.empty();
		}
	private:
		Container _con;
		
 		void AdjustUp(int child) {
			compare com;
			int parent = (child - 1) / 2;
			while (parent >= 0) {
				if (parent >= 0 && com(_con[child], _con[parent])) {
					swap(_con[child], _con[parent]);
					child = parent;
					parent = (child - 1) / 2;
				}
				else {
					break;
				}
			}
		}

		void AdjustDown(int root) {
			int child = (root * 2) + 1;
			int parent = root;
			compare com;
			while (child < _con.size()) {
				if (child + 1 < _con.size() && com(_con[child + 1], _con[child]))  {
					++child;
				}
				if (com(_con[child], _con[parent])) {
					swap(_con[parent], _con[child]);
					parent = child;
					child = (parent * 2) + 1;
				}
				else {
					break;
				}
			}
		}
	};
	
	template<class T>
	struct greater
	{
		bool operator()(const T& x1, const T& x2) {
			return x1 < x2;
		}
	};

	template<class T>
	struct less
	{
		bool operator()(const T& x1, const T& x2) {
			return x1 > x2;
		}
	};
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值