【C++优先级队列priority_queue基础】基本使用,模拟实现,堆

81 篇文章 2 订阅
65 篇文章 4 订阅

朋友们好,这篇博客我们继续C++的初阶学习,最近我学习了C++中的STL库中的优先级队列(priority_queue)容器适配器,对于优先级队列,我们不仅要会使用常用的函数接口,我们还有明白这些接口在其底层是如何实现的。所以特意整理出来一篇博客供我们学习和,如果文章中有理解不当的地方,还希望朋友们在评论区指出,我们相互学习,共同进步!

一:priority_queue的介绍

priority_queue官方文档介绍
在这里插入图片描述
翻译:

  1. 优先队列是一种容器适配器,根据严格的弱排序标准,它的第一个元素总是它所包含的元素中最大的
  2. 此上下文类似于堆,在堆中可以随时插入元素,并且只能检索最大堆元素(优先队列中位于顶部的元素)。
  3. 优先队列被实现为容器适配器,容器适配器即将特定容器类封装作为优先级队列的底层容器类,priority_queue提供一组特定的成员函数来访问其元素。元素从特定容器的“尾部"弹出,其称为优先队列的顶部。
  4. 底层容器可以是任何标准容器类模板,也可以是其他特定设计的容器类。容器应该可以通过随机访问迭代器访问,并支持以下操作:
    1️⃣empty():检测容器是否为空。
    2️⃣size():返回容器中有效元素个数。
    3️⃣front():返回容器中第一个元素的引用。
    4️⃣push_back():在容器尾部插入元素。
    5️⃣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。
  • top(),返回优先级队列中最大(最小)元素,即堆顶元素。
  • push(),在优先级队列中插入元素。
  • pop(),删除优先级队列中最大(最小)元素,即堆顶元素。

下面我们就举一个例子:
存放自定义类型,这样更具代表性!


template<class T>
class greater
{
public:
	bool operator()(const T& p1, const T& p2) const
	{
		return p1 > p2;
	}
};


struct person
{
	person(string name = "", int age = -1)
		:_name(name)
		, _age(age)
	{}

	bool operator<(const person& p) const
	{
		return _age < p._age;
	}
	bool operator>(const person& p) const
	{
		return _age > p._age;
	}

	string _name;
	int _age;
};

ostream& operator<<(ostream& out, const person& p)
{
	out << "name:" << p._name << "   " << "age:" << p._age << endl;
	return out;
}

void test02()
{
	person arr[] = { { "pxl", 23 },
					 { "dyx", 21 }, 
					 { "wjz", 24 }, 
					 { "ztd", 20 } };
	priority_queue<person, vector<person>, greater<person>> pq(arr, arr + sizeof(arr) / sizeof(arr[0]));//小堆
	pq.push(person("yzc", 22));
	
	cout <<"堆顶元素是:"<< pq.top() << endl;
	
	while (!pq.empty())
	{
		cout << pq.top() << endl;
		pq.pop();
	}
}

int main()
{
	test02();//自定义类型
	system("pause");
	return 0;
}

⚠️⚠️⚠️注意点:

  1. 如果存放自定义类型,我们想要自定义类型像内置类型一样进行各种运算,那么就要在类中重载相应的运算符
  2. 输出自定义类型,需要重载流输出
  3. 在priority_queue的第三个参数时,我们可以用库中的greater函数(头文件:functional),也可以我们自己写一个仿函数(如上述代码)。

三:priority_queue的模拟实现

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

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

	// 优先级队列 -- 大堆 < 小堆 >
	template<class T, class Container = vector<T>, class Compare = less<T>>
	class priority_queue
	{
	public:
		void AdjustUp(int child)
		{
			Compare comFunc;
			int parent = (child - 1) / 2;
			while (child > 0)
			{
				//if (_con[parent] < _con[child])
				if (comFunc(_con[parent], _con[child]))
				{
					swap(_con[parent], _con[child]);
					child = parent;
					parent = (child - 1) / 2;
				}
				else
				{
					break;
				}
			}
		}

		void push(const T& x)
		{
			_con.push_back(x);

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

		void AdjustDown(int parent)
		{
			Compare comFunc;
			size_t child = parent * 2 + 1;
			while (child < _con.size())
			{
				//if (child+1 < _con.size() && _con[child] < _con[child+1])
				if (child + 1 < _con.size() && comFunc(_con[child], _con[child + 1]))
				{
					++child;
				}

				//if (_con[parent] < _con[child])
				if (comFunc(_con[parent], _con[child]))
				{
					swap(_con[parent], _con[child]);
					parent = child;
					child = parent * 2 + 1;
				}
				else
				{
					break;
				}
			}
		}

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

			AdjustDown(0);
		}

		const T& top()
		{
			return _con[0];
		}

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

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

	private:
		Container _con;
	};

代码解释:

  1. 这里模拟实现底层容器缺省参数使用vector,比较规则使用Less。
  2. 这里的比较方式均是自己实现的仿函数。

四:容器适配器

4.1:什么是适配器

适配器是一种设计模式(设计模式是一套被反复使用的,多数人知晓的,经过分类编目的,代码设计经验的总结),该模式是讲一个类的接口转换成客户希望的另一个接口。

4.2:适配模式

  • 在计算机编程中,适配器模式(有时候也称包装样式或者包装)将一个类的接口适配成用户所期待的。一个适配允许通常因为接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。
  • 适配器模式主要应用于,当接口里定义的方法无法满足客户的需求,或者说接口里定义的方法的名称或者方法界面与客户需求有冲突的情况。
  • 两类模式:对象适配器模式 - 在这种适配器模式中,适配器容纳一个它我包裹的类的实例。在这种情况下,适配器调用被包裹对象的物理实体。类适配器模式 - 这种适配器模式下,适配器继承自已实现的类(一般多重继承)。
  • 在计算机编程中,适配器包括:容器适配器、迭代器适配器、泛函适配器等

4.3:STL标准库中stack和queue的底层结构

虽然stack和queue也可以存放元素,但是在STL中并没有将其划分在容器的行列,而是将其称为容器适配器,这是因为栈和队列只是对其他容器的接口进行了包装,STL中stack和queue默认使用deque,比如:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
当然了,这里的容器都是默认容器,容器不唯一,我们可以显式传对应的容器。

⭐️⭐️⭐️创作不易,还希望朋友们能三连支持,谢谢大家!!!

  • 17
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
好的,以下是使用C++实现队列模拟银行叫号系统并且有VIP队列的示例代码: ```c++ #include <iostream> #include <queue> using namespace std; // 定义顾客结构体 struct Customer { int number; bool is_vip; }; // 定义比较器,用于将VIP顾客插入到队列的最前面 struct Compare { bool operator() (const Customer& c1, const Customer& c2) { if (c1.is_vip != c2.is_vip) { return c1.is_vip > c2.is_vip; } else { return c1.number > c2.number; } } }; class Bank { public: Bank() { customer_number = 0; } // 新增一个顾客 void new_customer(bool is_vip) { Customer customer = {++customer_number, is_vip}; if (is_vip) { vip_queue.push(customer); } else { normal_queue.push(customer); } } // 叫下一个顾客 void serve_customer() { if (!vip_queue.empty()) { Customer customer = vip_queue.front(); vip_queue.pop(); cout << "Now serving customer " << customer.number << " (VIP)" << endl; } else if (!normal_queue.empty()) { Customer customer = normal_queue.front(); normal_queue.pop(); cout << "Now serving customer " << customer.number << endl; } else { cout << "No customers to serve." << endl; } } // 输出当前队列中的顾客号码 void show_queue() { cout << "VIP queue: "; queue<Customer> temp_queue = vip_queue; while (!temp_queue.empty()) { cout << temp_queue.front().number << " "; temp_queue.pop(); } cout << endl; cout << "Normal queue: "; temp_queue = normal_queue; while (!temp_queue.empty()) { cout << temp_queue.front().number << " "; temp_queue.pop(); } cout << endl; } private: int customer_number; priority_queue<Customer, vector<Customer>, Compare> vip_queue; queue<Customer> normal_queue; }; // 示例代码 int main() { Bank bank; bank.new_customer(false); bank.new_customer(true); bank.new_customer(false); bank.show_queue(); bank.serve_customer(); bank.show_queue(); bank.serve_customer(); bank.serve_customer(); bank.serve_customer(); bank.show_queue(); return 0; } ``` 在这个示例代码中,我们首先定义了一个顾客结构体,包含一个顾客号码和一个是否是VIP顾客的标记。然后我们定义了一个比较器Compare,用于将VIP顾客插入到队列的最前面。接着我们实现了一个Bank类来模拟银行,其中包含了三个方法: - new_customer:每次调用这个方法时,会为新的顾客生成一个号码,并将其加入到VIP队列或普通队列的末尾。 - serve_customer:每次调用这个方法时,会将队列中的下一个顾客叫到柜台处理。如果VIP队列非空,则优先叫VIP队列中的顾客;否则叫普通队列中的顾客。如果队列为空,则输出“No customers to serve.”的提示信息。 - show_queue:每次调用这个方法时,会输出当前VIP队列和普通队列中的顾客号码。 在示例代码的最后,我们创建了一个Bank对象,并调用了几个方法来测试它们的功能。您可以根据自己的需要修改代码来满足您的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值