模拟实现priority_queue

本文展示了如何使用模板类实现一个基于 std::vector 的优先级队列,并提供了两个示例,其中一个使用默认比较函数,另一个使用自定义比较函数 Greater<int>。通过 TestMyPriorityQueue1 和 TestMyPriorityQueue2 函数,演示了插入元素、弹出最大元素、获取顶部元素等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#pragma once

#include <vector>

namespace bite
{
	template<class T, class Container = std::vector<T>, class Com = std::less<T>>
	class priority_queue
	{
	public:
		priority_queue()
		{}

		template<class Iterator>
		priority_queue(Iterator first, Iterator last)
			: _con(first, last)
		{
			//将_con中的元素调整成堆

			//1.找调整的位置
			int size = _con.size();
			int root = ((size - 2) >> 1);
			for (; root >= 0; --root)
				_AdjustDown(root);
		}

		void push(const T& data)
		{
			_con.push_back(data);
			int child = _con.size() - 1;
			int parent = ((child - 1) >> 1);

			while (child)
			{
				if (Com()(_con[parent], _con[child]))
				{
					std::swap(_con[parent], _con[child]);
					child = parent;
					parent = ((child - 1) >> 1);
				}
				else
				{
					return;
				}
			}
		}

		void pop()
		{
			if (empty())
				return;

			std::swap(_con.front(), _con.back());
			_con.pop_back();

			_AdjustDown(0);
		}

		const T& top()const
		{
			return _con.front();
		}

		size_t size()const
		{
			return _con.size();
		}

		bool empty()const
		{
			return _con.empty();
		}
	private:
		void _AdjustDown(int parent)
		{
			//默认情况下:child标记左孩子
			size_t child = parent * 2 + 1;

			while (child < _con.size())
			{
				//找左右孩子中较大的孩子
				Com com;
				if (child + 1 < _con.size() && com(_con[child], _con[child]))
					child += 1;

				//用较大的孩子和双亲比较
				if (com(_con[parent], _con[child]))
				{
					std::swap(_con[parent], _con[child]);
					parent = child;
					child = parent * 2 + 1;
				}
				else
				{
					return;
				}
			}
		}

	private:
		Container _con;
	};
}

#include <iostream>
using namespace std;

void TestMyPriorityQueue1()
{
	bite::priority_queue<int> q;
	q.push(3);
	q.push(7);
	q.push(1);
	q.push(4);
	q.push(2);
	q.push(6);
	q.push(5);

	cout << q.size() << endl;
	cout << q.top() << endl;

	q.pop();
	cout << q.size() << endl;
	cout << q.top() << endl;
}

template<class T>
class Greater
{
public:
	bool operator()(const T& left, const T& right)
	{
		return left > right;
	}
};

void TestMyPriorityQueue2()
{
	bite::priority_queue<int, vector<int>, Greater<int>> q;
	q.push(3);
	q.push(7);
	q.push(1);
	q.push(4);
	q.push(2);
	q.push(6);
	q.push(5);

	cout << q.size() << endl;
	cout << q.top() << endl;

	q.pop();
	cout << q.size() << endl;
	cout << q.top() << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值