优先级队列

  优先级队列首先是一个队列,但是它强调的是“优先”,所以优先级队列又分为最大优先队列最小优先队列

  •  最大优先级队列:每次从队列中取出优先级最大的数据,删除数据也是删除优先级最大的数据。

  •  最小优先级队列:每次从队列中取出优先级最小的数据,删除也是删除优先级最小的数据。

  所以我们用一个类去实现优先级队列时就需要用到小顶堆和大顶堆的概念。我们并不关心除了最高优先级和最低优先级的数据在队列中是怎体存储的。

  为了提高代码的复用性,最大优先级对列和最小优先级队列都使用同一个堆调整函数,我们可以定义一个比较模板(Compare)也可以说是一个类,不过它是通过重载()实现的。

 

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

  通过Less和Grearter模板,我们就可以在优先级队列初始化的时候通过传Less或者Greater的对象,来调整是最大优先级队列还是最小优先级队列。

  我们的优先级队列所拥有的功能和STL源码的功能差不多。在这我是用一个顺序表来实现队列。以下是具体的实现

#pragma once
#include<iostream>
#include<vector>
using namespace std;

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,template<class> class Compare=Less>
class PQueue
{
public:
	PQueue()
		:_size(0)
	{}
	PQueue(const T* a, size_t size)
		:_size(size)
	{
		_data.resize(size);
		for (size_t i = 0; i < size; i++)
		{
			_data[i] = a[i];
		}
		for (int i = (size - 2) / 2; i >= 0; --i)
		{
			_AdjustDown(i);
		}
	}
	size_t Size()
	{
		return _size;
	}
	void Push(const T& d)
	{
		_data.push_back(d);
		++_size;
		_AdjustUp();
	}
	void Pop()
	{
		swap(_data[0], _data[_size - 1]);
		_data.pop_back();
		_AdjustDown(0);
	}
	T& Front()
	{
		return _data[0];
	}
	bool Empty()
	{
		return _size;
	}
protected:
	void _AdjustDown(int parent)
	{
		Compare<T> con;
		int child = parent * 2 + 1;
		while (child < _size)
		{
			if (child + 1 < _size&&con(_data[child + 1], _data[child]))
				++child;
			if (con(_data[child], _data[parent]))
			{
				swap(_data[child], _data[parent]);
				parent = child;
				child = parent * 2 + 1;
			}
			else
				break;
		}
	}
	void _AdjustUp(int child)
	{
		Compare<T> con;
		parent = (child - 1) / 2;
		while (child > 0)
		{
			if (con(_data[child], _data[parent]))
			{
				swap(_data[child], _data[parent]);
				child = parent;
				parent = (child - 1) / 2;
			}
			else
				break;
		}
	}
protected:
	vector<T> _data;
	size_t _size;
};

 优先级队列的核心就是调整大顶堆和小顶堆,如果对于大顶堆和小顶堆有不懂得话可以查看我的博客,互相交流学习。http://helloleex.blog.51cto.com/10728491/1768758

本文出自 “稻草阳光” 博客,请务必保留此出处http://helloleex.blog.51cto.com/10728491/1768895

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值