priority_queue实现

#include <algorithm>

using namespace std;
/*
priority_queue只允许在底端加入元素,并从顶端取出元素,
其内部元素不是依照被推入的次序排列,而是自动按照元素的权值排列,权值最大的元素排在最前面
缺省情况下priority_queue是利用一个max_heap完成.模板默认参数是vector,less. 
常用接口:top(), push(), pop(),类似栈的接口
*/ template <class T,class Sequence=vector<T>,class Compare=less<typename Sequence::value_type>> class priority_queue { public: typedef typename Sequence::value_type value_type; typedef typename Sequence::size_type size_type; typedef typename Sequence::reference reference; typedef typename Sequence::const_reference const_reference; protected: Sequence c;//底层容器 Compare comp;//元素大小比较标准 public: priority_queue() :c(){} explicit priority_queue(const Compare& x) :c(), comp(x){} //make_heap(),push_heap(),pop_heap()都是泛型算法 template <class InputIterator> priority_queue(InputIterator first, InputIterator last, const Compare& x) : c(first, last), comp(x) { make_heap(c.begin(), c.end(), comp); } template <class InputIterator> priority_queue(InputIterator first, InputIterator last) : c(first,last) { make_heap(c.begin(), c.end(), comp); } void push(const value_type &x) { __STL_TRY{ c.push_back(x); //重排heap push_heap(c.begin(), c.end(), comp); } __STL_UNWIND(c.clear()); } void pop() { __STL_TRY{ pop_heap(c.begin(), c.end(), comp); c.pop_back(); } __STL_UNWIND(c.clear()); } };

 

posted @ 2015-01-17 13:35  合唱团abc  阅读(314)  评论(0编辑  收藏  举报