【数据结构】模拟实现priority_queue

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();
		}

	
	
	}



}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值