STL中优先级队列本质上就是堆。在上一篇博客中讲到过:堆是一种完全二叉树,逻辑结构上看起来像树,但在物理结构中是存储在线性表中。与普通线性表不同的是,堆中数据大小是规律排列的:小堆中每个节点都大于它的父节点,大堆中每个节点都小于它的父节点。此时就造成小堆中的根节点一定是所有数据中最小的,而大堆中的根节点一定是所有数据中最大的。
#include<iostream>
using namespace std;
namespace yhy{#include<vector>#include<functional>template<class T>class less{bool operator()(const T& front, const T& back){return front < back;}};template<class T>class greater{bool operator()(const T& front, const T& back){return front > back;}};template <class T, class Container = vector<T>, class Compare = less<T> >class priority_queue{public:priority_queue(){}template <class InputIterator>priority_queue(InputIterator first, InputIterator last):c(first,last){for (size_t i = 1; i < c.size() - 1;i++){adjust_up(i);}}bool empty() const{return c.empty();}size_t size() const{return c.size();}T& top() const{return c[0];}void adjust_up(size_t i){while (i > 0){if (comp(c[(i-1)/2], c[i])){swap(c[i], c[(i - 1) / 2]);i = (i - 1) / 2;}elsebreak;}}void adjust_down(size_t i){size_t j = size();size_t child = i * 2 + 1;while (j > i){if (comp(c[child], c[child + 1]) && child < j){++child;}if (comp(c[i], c[child])){swap(c[i], c[(child]);i = i * 2 + 1;}elsebreak;}}void push(const T& x){c.push_back(x);adjust_up();}void pop(){swap(c[0], c[c.size() - 1]);adjust_down();}private:Container c;Compare comp;};};