priority_queue的模拟实现

1. priority_queue的介绍和使用

1.1 priority_queue的介绍

  1. 优先队列是一种容器适配器,根据严格的弱排序标准,它的第一个元素总是它所包含的元素中最大的。
  2. 此上下文类似于堆,在堆中可以随时插入元素,并且只能检索最大堆元素(优先队列中位于顶部的元素)。
  3. 优先队列被实现为容器适配器,容器适配器即将特定容器类封装作为其底层容器类,queue提供一组特定的成员函数来访问其元素。元素从特定容器的“尾部”弹出,其称为优先队列的顶部。
  4. 底层容器可以是任何标准容器类模板,也可以是其他特定设计的容器类。容器应该可以通过随机访问迭代器访问,并支持以下操作:
  • empty():检测容器是否为空
  • size():返回容器中有效元素个数
  • front():返回容器中第一个元素的引用
  • push_back():在容器尾部插入元素
  • pop_back():删除容器尾部元素
  1. 标准容器类vector和deque满足这些需求。默认情况下,如果没有为特定的priority_queue类实例化指定容器类,则使用vector。
  2. 需要支持随机访问迭代器,以便始终在内部保持堆结构。容器适配器通过在需要时自动调用算法函数make_heap、push_heap和pop_heap来自动完成此操作。

1.2 priority_queue的使用

优先级队列默认使用vector作为其底层存储数据的容器,在vector上又使用了堆算法将vector中元素构造成堆的结构,因此priority_queue就是堆,所有需要用到堆的位置,都可以考虑使用priority_queue。

注意:默认情况下priority_queue是大堆。

在这里插入图片描述

在这里插入图片描述

#include <iostream>

using namespace std;

#include <queue>

int main()
{
	//默认是大堆 -- 大的优先级高
	//priority_queue<int> q
	
	priority_queue<int> q;
	q.push(1);
	q.push(3);
	q.push(4);
	q.push(2);

	while (!q.empty())
	{
		cout << q.top() << " ";
		q.pop();
	}

	cout << endl;

	return 0;
}

运行结果如图:
在这里插入图片描述
默认是大堆,传的是less<T>如果我们希望使用小堆就要自己传一个仿函数

int main()
{
	priority_queue<int,vector<int>,greater<int>> q;
	q.push(1);
	q.push(3);
	q.push(4);
	q.push(2);

	while (!q.empty())
	{
		cout << q.top() << " ";
		q.pop();
	}

	cout << endl;

	return 0;
}

运行结果如图:
在这里插入图片描述

2. priority_queue的模拟实现

通过对priority_queue的底层结构就是堆,因此此处只需对对进行通用的封装即可

namespace hb
{
	template<class T,class Continer = vector<T>>
	//大堆
	class priority_queue
	{
	public:
		void push(const T& x)
		{
			_con.push_back(x);

			adjust_up(_con.size() - 1);
		}

		void adjust_up(int child)
		{
			int parent = (child - 1) / 2;

			while (child > 0)
			{
				if (_con[child] > _con[parent])
				{
					swap(_con[child], _con[parent]);

					child = parent;
					parent = (child - 1) / 2;
				}
				else
				{
					break;
				}
			}
		}

		void adjust_down(int parent)
		{
			int child = parent * 2 + 1;

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

			while (child < _con.size())
			{
				if (_con[child] > _con[parent])
				{
					swap(_con[child], _con[parent]);

					parent = child;

					child = parent * 2 + 1;
				}
				else
				{
					break;
				}
			}
		}

		void pop()
		{
			swap(_con[0], _con[_con.size() - 1]);
			_con.pop_back();

			adjust_down(0);
		}

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

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

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

	private:
		Continer _con;
	};
}

代码测试:

int main()
{
	priority_queue<int> q;
	
	q.push(1);
	q.push(3);
	q.push(4);
	q.push(2);

	while (!q.empty())
	{
		cout << q.top() << " ";
		q.pop();
	}

	cout << endl;


	return 0;
}

运行结果如图:
在这里插入图片描述

但是如果我们希望把大堆变成小堆就需要改变代码的比较方式,所以这里我们我们可以增加一个模板参数,通过这个模板参数来控制比较的方式,所以这里就要用到仿函数。

namespace hb
{
	template<class T>
	struct Less
	{
		bool operator()(const T& x, const T& y)
		{
			return x < y;
		}
	};

	template<class T>
	struct Greater
	{
		bool operator()(const T& x, const T& y)
		{
			return x > y;
		}
	};

	template<class T, class Continer = vector<T>,class Compare = Less<T>>
	class priority_queue
	{
	public:
		void push(const T& x)
		{
			_con.push_back(x);

			adjust_up(_con.size() - 1);
		}

		void adjust_up(int child)
		{
			Compare compare;

			int parent = (child - 1) / 2;

			while (child > 0)
			{
				if (compare(_con[parent],_con[child]))
				{
					swap(_con[child], _con[parent]);

					child = parent;
					parent = (child - 1) / 2;
				}
				else
				{
					break;
				}
			}
		}

		void adjust_down(int parent)
		{
			Compare compare;

			int child = parent * 2 + 1;

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

			while (child < _con.size())
			{
				if (compare(_con[parent], _con[child]))
				{
					swap(_con[child], _con[parent]);

					parent = child;

					child = parent * 2 + 1;
				}
				else
				{
					break;
				}
			}
		}

		void pop()
		{
			swap(_con[0], _con[_con.size() - 1]);
			_con.pop_back();

			adjust_down(0);
		}

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

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

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

	private:
		Continer _con;
	};
}

代码测试:

int main()
{
	priority_queue<int,vector<int>,hb::Greater<int>> q;
	
	q.push(1);
	q.push(3);
	q.push(4);
	q.push(2);

	while (!q.empty())
	{
		cout << q.top() << " ";
		q.pop();
	}

	cout << endl;


	return 0;
}

运行结果如图:
在这里插入图片描述

如果在priority_queue中放自定义类型的数据,用户需要在自定义类型中提供> 或者< 的重载。

class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
		: _year(year)
		, _month(month)
		, _day(day)
	{}

	bool operator<(const Date& d)const
	{
		return (_year < d._year) ||
			(_year == d._year && _month < d._month) ||
			(_year == d._year && _month == d._month && _day < d._day);
	}

	bool operator>(const Date& d)const
	{
		return (_year > d._year) ||
			(_year == d._year && _month > d._month) ||
			(_year == d._year && _month == d._month && _day > d._day);
	}

	friend ostream& operator<<(ostream& _cout, const Date& d)
	{
		_cout << d._year << "-" << d._month << "-" << d._day;
		return _cout;
	}

private:
	int _year;
	int _month;
	int _day;
};

在这里插入图片描述

如果是以下这种情况呢

在这里插入图片描述

虽然指针也可以比较大小,但是指针比较大小的方式是按照地址的大小来比较,显然不符合我们的预期,我们希望的是比较指针解引用的内容。

所以再写一个专门用来比较指针解引用的仿函数

template<class T>
struct LessDate
{
	bool operator()(const T& x, const T& y)
	{
		return *x < *y;
	}
};

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

3. 堆排序

void adjust_down(vector<int>& v,int parent,int n)
{
	int child = parent * 2 + 1;

	if (child + 1 < n && v[child + 1] > v[child])
	{
		child++;
	}

	while (child < n)
	{
		if (v[child] > v[parent])
		{
			swap(v[child], v[parent]);

			parent = child;

			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

void HeapSort(vector<int>& v)
{
	//向下调整建堆
	for (int i = (v.size() - 1 - 1) / 2; i >= 0; i--)
	{
		adjust_down(v,i,v.size());
	}

	//升序建大堆
	/*swap(v[0], v[v.size() - 1]);
	adjust_down(v, 0,v.size() - 1);*/

	for (int i = v.size() - 1; i > 0; i--)
	{
		swap(v[0], v[i]);
		adjust_down(v, 0, i);
	}

}

代码测试:

void test()
{
	vector<int> v = { 1,4,3,2,4,6 };
	HeapSort(v);

	for (auto e : v)
	{
		cout << e << " ";
	}
	cout << endl;
}

运行结果如图:
在这里插入图片描述

评论 25
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

星光终将不负赶路人

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

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

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

打赏作者

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

抵扣说明:

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

余额充值