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

来源:互联网 发布:数据透视图显示百分比 编辑:程序博客网 时间:2024/06/07 06:02

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 0