C++数据结构 之 优先队列_Priority Queue

C++数据结构 之 优先队列_Priority Queue

源代码只包含头文件

注:需要C++11的支持

一、优先队列优先

队列的思想和队列是不同的,并不是先进先出,元素在入队列之后,有一个排序的过程:按照优先级,谁的优先级高就排在前面。但它的结构和队列类似。

它支持如下几个操作:
1、push (入队列):将元素从队列的末尾压入队列。
2、pop (出队列):将元素从队列的首位从元素取出。
3、top 返回最首位的元素,但是不出队列。

二、源代码:

#ifndef PRIORITY_QUEUE_H
#define PRIORITY_QUEUE_H

#include <vector>
#include <algorithm>
#include <functional>

using std::make_heap;
using std::pop_heap;
using std::push_heap;

template <
	typename T,
	typename Container = std::vector<T>,
	typename Compare = std::less<typename Container::value_type>>
	class Priority_Queue {
	public:
		typedef typename Container::size_type size_type;
		typedef typename Container::value_type value_type;
		typedef typename Container::const_reference const_reference;

	public:
		Priority_Queue() = default;
		Priority_Queue(const Priority_Queue &s) : c(s.c), comp(s.comp){}
		Priority_Queue& operator=(const Priority_Queue &s) {
			c = s.c;
			comp = s.comp;
			return *this;
		}
		template<class T>
		    Priority_Queue(T First, T Last) : c(First, Last), comp() {
			make_heap(c.begin(), c.end(), comp);
		}

		Priority_Queue(const Container& cont) : c(cont) {
			make_heap(c.begin(), c.end(), comp);
		}

		Priority_Queue(const Compare& cmp, const Container& cont) : comp(cmp), c(cont) {
			make_heap(c.begin(), c.end(), comp);
		}

		~Priority_Queue() = default;

		void push(value_type&& x) {
			c.push_back(move(x));
			push_heap(c.begin(), c.end(), comp);
		}

		void push(const value_type& x) {
			c.push_back(x);
			push_heap(c.begin(), c.end(), comp);
		}

		const_reference& top() const {
			return c.front();
		}
		void pop() {
			pop_heap(c.begin(), c.end(), comp);
			c.pop_back();
		}

		bool empty() const {
			return c.empty();
		}

		size_type size() const {
			return c.size();
		}

	private:
		Container c;
		Compare comp;
};

#endif // !PRIORITY_QUEUE_H

注解:
本优先队列是基于vector(向量)实现的,并作用在heap(堆)上,以实现排序目的。Compare是一个比较子,它是按照数据类型的less函数对象实现的,从而确定了优先级。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值