【C++】优先级队列与仿函数

目录

一、优先级队列介绍与使用

1、priority_queue介绍

2、priority_queue的使用

二、仿函数

1、仿函数编写与使用

三、priority_queue模拟实现

四、扩展内容


一、优先级队列介绍与使用

1、priority_queue介绍

 1、优先队列是一种容器适配器,根据严格的弱排序标准,它的第一个元素总是它所包含的元素中最大的。
 2、此上下文类似于堆,在堆中可以随时插入元素,并且只能检索最大堆元素(优先队列中位于顶部的元素)。
 3、优先队列被实现为容器适配器,容器适配器即将特定容器类封装作为其底层容器类,queue提供一组特定的成员函数来访问其元素。元素从特定容器的“尾部”弹出,其称为优先队列的顶部。
 4、底层容器可以是任何标准容器类模板,也可以是其他特定设计的容器类。容器应该可以通过随机访问迭代器访问,并支持以下操作:

扫描二维码关注公众号,回复: 14767275 查看本文章
  • empty():检测容器是否为空
  • size():返回容器中有效元素个数
  • front():返回容器中第一个元素的引用
  • push_back():在容器尾部插入元素
  • pop_back():删除容器尾部元素

 5、标准容器类vector和deque满足这些需求。默认情况下,如果没有为特定的priority_queue类实例化指定容器类,则使用vector。
 6、需要支持随机访问迭代器,以便始终在内部保持堆结构。容器适配器通过在需要时自动调用算法函数make_heap、push_heap和pop_heap来自动完成此操作。

2、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() 删除优先级队列中最大(最小)元素,即堆顶元素

 可以看到 priority_queue 默认较大的数字优先级更高,即默认为大堆。

 如果想要使优先级队列中,小的优先级更高,则可以借助仿函数来实现。

二、仿函数

使用仿函数需要包含头文件 functional

可以实现优先级队列中小的优先级更高。 

1、仿函数编写与使用

仿函数有一个特点,就是都重载了一个 "()" 运算符:

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

使用方法如下:

 看 lessFunc 的用法,他好像是一个函数,但实际上他是一个类实例化出的对象。我们把这个类称为仿函数,仿函数的对象可以像函数一样使用。

三、priority_queue模拟实现

 priority_queue的底层是使用堆来实现的,具体关于堆的内容可以参考文章《堆——一种特殊的二叉树结构》

具体代码如下:

namespace bin
{
	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 Container = vector<T>, class Compare = less<T>>
	class priority_queue
	{
	public:
		void adjust_up(int child)
		{
			Compare com;
			int parent = (child - 1) / 2;
			while (child > 0)
			{
				//if (_con[parent] < _con[child])
				if (com(_con[parent], _con[child]))
				{
					swap(_con[child], _con[parent]);
					child = parent;
					parent = (child - 1) / 2;
				}
				else
				{
					break;
				}
			}
		}

		void adjust_down(int parent)
		{
			int child = parent * 2 + 1;
			while (child < _con.size())
			{
				Compare com;
				//if (child + 1 < _con.size() && _con[child] < _con[child + 1])
				if (child + 1 < _con.size() && com(_con[child], _con[child + 1]))
				{
					++child;
				}
				//if (_con[parent] < _con[child])
				if (com(_con[parent], _con[child]))
				{
					swap(_con[child], _con[parent]);
					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];
		}

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

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

	private:
		Container _con;
	};
}

测试结果正确: 

四、扩展内容

对于仿函数,我们可以自由的指定其比较方式,如以下场景:

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

class PDataLess
{
public:
	bool operator()(const Date* p1, const Date* p2)
	{
		return *p1 < *p2;
	}
};

class PDataGreater
{
public:
	bool operator()(const Date* p1, const Date* p2)
	{
		return *p1 > *p2;
	}
};

void TestPriorityQueue()
{
	priority_queue<Date*, vector<Date*>, PDataGreater> q;
	q.push(new Date(2023, 4, 8));
	q.push(new Date(2023, 4, 9));
	q.push(new Date(2023, 4, 7));
	cout << q.top() << endl;
}

 我们设定的优先级队列的成员变量类型为指针类型,但是我们希望他们的比较方案是比较他们解引用后的数据,这就可以通过设置仿函数内的比较策略来完成目的:


 关于优先级队列的内容就讲到这里,希望同学们多多支持,如果有不对的地方欢迎大佬指正,谢谢!

猜你喜欢

转载自blog.csdn.net/weixin_74078718/article/details/130017530