优先级队列,顾名思义。就是一种依据一定优先级存储和取出数据的队列。它能够说是队列和排序的完美结合体。不仅能够存储数据。还能够将这些数据依照我们设定的规则进行排序。
优先级队列是堆的一种常见应用。有最大优先级队列(最大堆)和最小优先级队列(最小堆)。优先级队列是一种维护有一组元素构成的集合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
}
他的模板声明带有三个參数:
priority_queue<Type, Container, Functional>
当中Type 为数据类型, Container 为保存数据的容器,Functional 为元素比較方式。
Container 必须是用数组实现的容器。比方 vector, deque 但不能用 list.
STL里面默认用的是 vector. 比較方式默认用 operator< , 所以假设你把后面俩个參数缺省的话,
优先队列就是大顶堆,队头元素最大。
#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
}
详细实例:点击打开链接
原文:http://www.cnblogs.com/gcczhongduan/p/5260736.html