priority_queue 模拟实现

priority_queue(优先队列)是一种特殊的队列数据结构,它的每个元素都有一个与之关联的优先级。在优先队列中,元素按照优先级的顺序进行排列,具有较高优先级的元素排在前面,较低优先级的元素排在后面。
C++标准库中的priority_queue:
priority_queue
下面是riority_queue的简单模拟实现:

#pragma once
#include <vector>
#include <iostream>
using namespace std;
namespace hsl
{
	template<class T, class Container = vector<T>,class Compar = Less<T>>
	class priority_queue
	{
	public:
		priority_queue()
		{}
		template <class InputIterator>
		priority_queue(InputIterator first, InputIterator last)
			:_con(first, last)
		{
			for (int i = (_con.size() - 2) / 2; i >= 0; i--)
			{
				adjust_down();
			}
		}


		void adjust_up(int child)
		{
			Compar com;
			int parent = (child - 1) / 2;
			while (child > 0)
			{
				//if (_con[parent] < _con[child])
				if(com(_con[parent],_con[child]))
				{
					swap(_con[parent], _con[child]);
					child = parent;
					parent = (child - 1) / 2;
				}
				else
				{
					break;
				}
			}
		}
		void adjust_down(size_t parent)
		{
			Compar com;
			size_t child = parent * 2 + 1;
			while (child < _con.size())
			{


				if (child + 1 < _con.size() && com(_con[child] , _con[child + 1]))
				{
					++child;
				}


				if (com(_con[parent] , _con[child]))
				{
					swap(_con[parent], _con[child]);
					parent = child;
					child = parent * 2 + 1;
				}
				else
				{
					break;
				}
			}
		}
		void push(const T& x)
		{
			_con.push_back(x);
			adjust_up(_con.size()-1);
		}
		void pop()
		{
			swap(_con[0], _con[_con.size() - 1]);
			_con.pop_back();
			adjust_down(0);
		}


		const T& top()
		{
			return _con[0];
		}


		bool empty()
		{
			return _con.empty();
		}
		size_t size()
		{
			return _con.size();
		}
	private:
		Container _con;
	};
	template<class T>
	class Less
	{
	public:
		const T& operator()(const T& a, const T& b)
		{
			return a < b;
		}
	};


	template<class T>
	class Greater
	{
	public:
		const T& operator()(const T& a, const T& b)
		{
			return a > b;
		}
	};
}	
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

originalHSL.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值