C++优先级队列

目录

一、priority_queue的介绍

二、priority_queue的使用

三、priority_queue的模拟实现


一、priority_queue的介绍

1、优先队列是一种容器适配器,根据严格的弱排序标准,它的第一个元素总是它所包含的元素中最大的。

2、此上下文类似于堆,在堆中可以随时插入元素,并且只能检索最大堆元素(优先队列中位于顶部的元素)。

3、优先队列被实现为容器适配器,容器适配器即将特定容器类封装作为其底层容器类,queue提供一组特定的成员函数来访问其元素。元素从特定容器的“尾部”弹出,其称为优先队列的顶部。

4、底层容器可以是任何标准容器类模板,也可以是其他特定设计的容器类。容器应该可以通过随机访问迭代器访问,并支持以下操作:
empty():检测容器是否为空

size():返回容器中有效元素个数

front():返回容器中第一个元素的引用

push_back():在容器尾部插入元素、

pop_back():删除容器尾部元素

5、标准容器类vector和deque满足这些需求。默认情况下,如果没有为特定的priority_queue类实例化指定容器类,则使用vector。

6、需要支持随机访问迭代器,以便始终在内部保持堆结构。容器适配器通过在需要时自动调用算法函数
make_heap、push_heap和pop_heap来自动完成此操作。

二、priority_queue的使用

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

函数声明接口说明
priority_queue()/priority_queue(first,
last)
构造一个空的优先级队列
empty( )检测优先级队列是否为空,是返回true,否则返回
false
top( )返回优先级队列中最大(最小元素),即堆顶元素
push(x)在优先级队列中插入元素x
pop()删除优先级队列中最大(最小)元素,即堆顶元素

优先级队列的基本使用方法(针对基本数据类型)

#include <iostream>
#include <queue>
#include <vector>
#include <functional> // greater算法的头文件
using namespace std;
void TestPriorityQueue()
{
	// 默认情况下,创建的是大堆,其底层按照小于号比较
	vector<int> v{ 3,2,7,6,0,4,1,9,8,5 };
	priority_queue<int> q1;
	for (auto& e : v)
		q1.push(e);
	cout << q1.top() << endl;
	// 如果要创建小堆,将第三个模板参数换成greater比较方式
	priority_queue<int, vector<int>, greater<int>> q2(v.begin(), v.end());
	cout << q2.top() << endl;
}
int main()
{
	TestPriorityQueue();
	return 0;
}

对于自定义的数据类型的使用方法如下

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

#include <iostream>
#include <queue>
#include <vector>
#include <functional> // greater算法的头文件
using namespace std;
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;
};
void TestPriorityQueue()
{
	// 大堆,需要用户在自定义类型中提供<的重载
	priority_queue<Date> q1;
	q1.push(Date(2018, 10, 29));
	q1.push(Date(2018, 10, 28));
	q1.push(Date(2018, 10, 30));
	cout << q1.top() << endl;
	// 如果要创建小堆,需要用户提供>的重载
	priority_queue<Date, vector<Date>, greater<Date>> q2;
	q2.push(Date(2018, 10, 29));
	q2.push(Date(2018, 10, 28));
	q2.push(Date(2018, 10, 30));
	cout << q2.top() << endl;
}
int main()
{
	TestPriorityQueue();
	return 0;
}

三、priority_queue的模拟实现

#include <iostream>
#include <vector>
using namespace std;
namespace priority_queue
{
	template <class T>
	struct Less
	{
		bool operator() (const T& left, const T& right)
		{
			return left < right;
		}
	};
	template <class T>
	struct Greater
	{
		bool operator() (const T& left, const T& right)
		{
			return left > right;
		}
	};
	template <class T, class Container = vector<T>, class Compare = less<T>>//默认建立大堆
	class priority_queue
	{
	private:
		Container _con;
		Compare _cmp;
		void adjust_down(size_t parent)
		{
			size_t child = parent * 2 + 1;
			while (child < size())
			{
				if (child + 1 < size() && _cmp(_con[child], _con[child + 1]))
				{
					child += 1;
				}
				if (_cmp(_con[parent], _con[child]))
				{
					swap(_con[child], _con[parent]);
					parent = child;
					child = parent * 2 + 1;
				}
				else
				{
					break;
				}
			}
		}
		void adjust_up(size_t child)
		{
			size_t parent = (child - 1) / 2;
			while (child > 0)
			{
				if (_cmp(_con[parent], _con[child]))
				{
					swap(_con[child], _con[parent]);
					child = parent;
					parent = (child - 1) / 2;
				}
				else
				{
					break;
				}
			}
		}
	public:
		priority_queue()
		{}
		template <class InputIterator>
		priority_queue(InputIterator first, InputIterator last)
		{
			while (first != last)
			{
				push(*first);
				first++;
			}
		}
		void push(const T& d)
		{
			_con.push_back(d);
			adjust_up(size() - 1);
		}
		bool empty() const
		{
			return size() == 0;
		}
		size_t size() const
		{
			return _con.size();
		}
		void pop()
		{
			swap(_con[0], _con[size() - 1]);
			_con.pop_back();
			adjust_down(0);
		}
		const T& top() const
		{
			return _con[0];
		}
	};
	class Date
	{
	public:
		Date(int year, int month, int day)
			:_year(year),
			_month(month),
			_day(day)
		{}
		void print()const
		{
			cout << _year << "-" << _month << "-" << _day << endl;
		}
		bool operator< (const Date& d)const
		{
			if (_year < d._year)
			{
				return true;
			}
			else if (_year == d._year && _month < d._month)
			{
				return true;
			}
			else if (_year == d._year && _month == d._month && _day < d._day)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		bool operator> (const Date& d)const
		{
			if (_year > d._year)
			{
				return true;
			}
			else if (_year == d._year && _month > d._month)
			{
				return true;
			}
			else if (_year == d._year && _month == d._month && _day > d._day)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		int _year;
		int _month;
		int _day;
	};
	void priority_queue_test()
	{
		//priority_queue<int, vector<int>, Less<int>> pq;
		//pq.push(3);
		//pq.push(2);
		//pq.push(5);
		//pq.push(6);
		//pq.push(7);
		//pq.push(9);
		//while (!pq.empty())
		//{
		//	cout << pq.top() << endl;
		//	pq.pop();
		//}
		priority_queue<Date, vector<Date>, Less<Date>> pq;
		pq.push(Date(2022, 6, 21));
		pq.push(Date(1949, 10, 1));
		pq.push(Date(1976, 5, 4));
		pq.push(Date(1999, 6, 21));
		pq.push(Date(2008, 1, 1));
		pq.push(Date(2018, 1, 1));
		while (!pq.empty())
		{
			cout << pq.top()._year << "-" << pq.top()._month << "-" << pq.top()._day << endl;
			//pq.top().print();
			pq.pop();
		}
	}
};
int main()
{
	priority_queue::priority_queue_test();
	return 0;
}
  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值