优先级队列,顾名思义,就是一种根据一定优先级存储和取出数据的队列。它可以说是队列和排序的完美结合体,不仅可以存储数据,还可以将这些数据按照我们设定的规则进行排序。优先级队列是堆的一种常见应用。有最大优先级队列(最大堆)和最小优先级队列(最小堆)。优先级队列是一种维护有一组元素构成的集合S的数据结构。
priority_queue调用 STL里面的 make_heap(), pop_heap(), push_heap() 算法实现,也算是堆的另外一种形式。
用make_heap(), pop_heap(), push_heap() 简单实现一个最大优先级队列
/********************************* * 日期:2015-01-06 * 作者:SJF0115 * 题目: 简单实现最大优先级队列 * 博客: **********************************/ #include <iostream> #include <algorithm> #include <vector> using namespace std; //简单实现最大优先级队列 template<typename T> class priority_queue{ private: // 数据 vector<T> data; public: // 进队列 void push(T val){ data.push_back(val); push_heap(data.begin(),data.end()); } // 出队列 void pop(){ pop_heap(data.begin(),data.end()); data.pop_back(); } // 头元素 T top(){ return data.front(); } // 大小 int size(){ return data.size(); } // 是否为空 bool empty(){ return data.empty(); } }; int main(){ priority_queue<char> heap; heap.push('5'); heap.push('4'); heap.push('3'); heap.push('9'); heap.push('6'); while(!heap.empty()){ cout<<heap.top()<<endl; heap.pop(); }//while }
#include <iostream> #include <queue> using namespace std; int main(){ priority_queue<char> heap; heap.push('5'); heap.push('4'); heap.push('3'); heap.push('9'); heap.push('6'); // 输出最大优先级队列 while(!heap.empty()){ cout<<heap.top()<<endl; heap.pop(); }//while }
#include <iostream> #include <queue> using namespace std; int main(){ // 最小优先级队列 priority_queue<char,vector<char>,greater<char> > heap; heap.push('5'); heap.push('4'); heap.push('3'); heap.push('9'); heap.push('6'); // 输出最大优先级队列 while(!heap.empty()){ cout<<heap.top()<<endl; heap.pop(); }//while }
注意:
自定义类型重载 operator< 后,声明对象时就可以只带一个模板参数。
但此时不能像基本类型这样声明priority_queue<Node, vector<Node>, greater<Node> >;
原因是 greater<Node> 没有定义,如果想用这种方法定义则可以按如下方式:
#include <iostream> #include <queue> using namespace std; struct Node{ int value; int key; Node(int x,int y):key(x),value(y){} }; struct cmp{ bool operator()(Node a,Node b){ if(a.key == b.key){ return a.value > b.value; } return a.key > b.key; } }; int main(){ priority_queue<Node,vector<Node>,cmp> heap; Node node0(5,6); Node node1(3,3); Node node2(2,4); Node node3(2,3); Node node4(1,3); heap.push(node0); heap.push(node1); heap.push(node2); heap.push(node3); heap.push(node4); while(!heap.empty()){ Node node = heap.top(); cout<<"Key->"<<node.key<<" Value->"<<node.value<<endl; heap.pop(); }//while }
具体实例:点击打开链接
看病要排队
搬水果