装载自http://blog.csdn.net/tianshuai1111/article/details/7652553

一,概述

priority_queue是拥有权值观念的queue,它允许加入新元素,移除旧元素。调用 STL里面的 make_heap(), pop_heap(), push_heap() 算法实现,也算是堆的另外一种形式。但它是一个queue所以只允许在底端加入元素,在顶端移除元素。

排序:按照权值大小顺序排序,而不是按照push 进去的顺序排序。权值高者排在前面,权值低者排在后面。

允许以任何大小顺序插入到优先队列,但取出时是按照权值大小取。

二,heap(堆)简介

1)采用vector存储,是一颗完全二叉树(complete binary tree)的形式。

heap分为 max_heap 和 min_heap,前者最大权值在根,后者最小权值在根。

2)建立堆过程

vector中元素先调整为堆的形式。

插入元素时,将元素放到vector 的最后面end(),然后上溯调整堆。

3)heap算法      // #include <algorithm>

make_heap(first,last)       //初建堆

push_heap(first,last)        //插入元素,并调整为堆

pop_heap(first,last)         //弹出元素,并调整为堆

sort_heap(first,last)         //堆排序

4)示例

 #include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm> using namespace std; int main(int argc, char** argv) { int ia[]={,,,,,,,,};
vector<int> ivec(ia,ia+); make_heap(ivec.begin(),ivec.end()); //#include <algorithm>
for(int i=;i<ivec.size();++i)
cout<<ivec[i]<<" ";
cout<<endl; ivec.push_back();
push_heap(ivec.begin(),ivec.end());
for(int i=;i<ivec.size();++i)
cout<<ivec[i]<<" ";
cout<<endl; pop_heap(ivec.begin(),ivec.end());
cout<<ivec.back()<<endl; //返回刚刚弹出的堆顶
ivec.pop_back(); //将最后一个元素弹出数组 for(int i=;i<ivec.size();++i)
cout<<ivec[i]<<" ";
cout<<endl; sort_heap(ivec.begin(),ivec.end());
for(int i=;i<ivec.size();++i)
cout<<ivec[i]<<" ";
cout<<endl; return ;
}

三,priority_queue 实例

 #include <queue>
#include <algorithm>
#include <iostream>
using namespace std; int main(int argc, char** argv) { int ia[]={,,,,,,,,};
priority_queue<int> ipq(ia,ia+);
cout<<"size:"<<ipq.size()<<endl; for(int i=;i<ipq.size();++i)
cout<<ipq.top()<<" ";
cout<<endl; while(!ipq.empty())
{
cout<<ipq.top()<<" ";
ipq.pop();
} return ;
}

2)自己实现priority_queue

STL里面的 priority_queue 写法与此相似,只是增加了模板及相关的迭代器

 #include <iostream>
#include <algorithm>
#include <vector> using namespace std;
class priority_queue
{
private:
vector<int> data;
public:
void push( int t ){
data.push_back(t);
push_heap( data.begin(), data.end());//将动态数组vector中元素 建立成堆
}
void pop(){
pop_heap( data.begin(), data.end() ); //弹出堆顶元素,并调整堆
data.pop_back();
}
int top() { return data.front(); }
int size() { return data.size(); }
bool empty() { return data.empty(); }
}; int main()
{
priority_queue test;
test.push( );
test.push( );
test.push( );
test.push( ); while( !test.empty() ){
cout << test.top() << endl;
test.pop(); } return ; }

3)STL里面默认用的是 vector. 比较方式默认用 operator< , 所以如果你把后面俩个参数缺省的话,优先队列就是大顶堆,队头元素最大。如果要用到小顶堆,则一般要把模板的三个参数都带进去。STL里面定义了一个仿函数 greater<>,对于基本类型可以用这个仿函数声明小顶堆

 #include <iostream>
#include <queue>
#include <cstdlib> using namespace std; int main(){ priority_queue<int, vector<int>, greater<int> > q; for( int i= ; i< ; ++i ) q.push( rand() );
while( !q.empty() ){
cout << q.top() << endl;
q.pop();
} return ;
}

4)对于自定义类型,则必须自己重载 operator< 或者自己写仿函数

 #include <iostream>
#include <queue>
#include <cstdlib> using namespace std; struct Node{
int x, y;
Node( int a= , int b= ):x(a), y(b) {} //初始化
}; bool operator<( Node a, Node b ){
if( a.x== b.x )
return a.y> b.y;
else
return a.x> b.x;
} int main(){
priority_queue<Node> q; for( int i= ; i< ; ++i )
q.push( Node( rand(), rand() ) ); while( !q.empty() ){
cout << q.top().x << ' ' << q.top().y << endl;
q.pop();
} return ;
}

5)自定义类型重载 operator< 后,声明对象时就可以只带一个模板参数。但此时不能像基本类型这样声明priority_queue<Node, vector<Node>, greater<Node> >;原因是 greater<Node> 没有定义,如果想用这种方法定义则可以按如下方式:

 #include <iostream>
#include <queue> using namespace std; struct Node{
int x, y;
Node( int a= , int b= ):
x(a), y(b) {}
}; struct cmp{
bool operator() ( Node a, Node b ){
if( a.x== b.x ) return a.y> b.y; return a.x> b.x; }
}; int main(){
priority_queue<Node, vector<Node>, cmp> q; for( int i= ; i< ; ++i )
q.push( Node( rand(), rand() ) ); while( !q.empty() ){
cout << q.top().x << ' ' << q.top().y << endl;
q.pop();
} getchar();
return ;
}

要注意的是,如果重载cmp,return a > b的形式形成的堆堆顶为最小元素!!

(转)【C++ STL】细数C++ STL 的那些事 -- priority_queue(优先队列)的更多相关文章

  1. 泛型编程、STL的概念、STL模板思想及其六大组件的关系,以及泛型编程(GP)、STL、面向对象编程(OOP)、C++之间的关系

    2013-08-11 10:46:39 介绍STL模板的书,有两本比较经典: 一本是<Generic Programming and the STL>,中文翻译为<泛型编程与STL& ...

  2. 细数iOS上的那些安全防护

    细数iOS上的那些安全防护  龙磊,黑雪,蒸米 @阿里巴巴移动安全 0x00 序 随着苹果对iOS系统多年的研发,iOS上的安全防护机制也是越来越多,越来越复杂.这对于刚接触iOS安全的研究人员来说非 ...

  3. 细数.NET 中那些ORM框架 —— 谈谈这些天的收获之一

    细数.NET 中那些ORM框架 —— 谈谈这些天的收获之一(转) ADO.NET Entity Framework        ADO.NET Entity Framework 是微软以 ADO.N ...

  4. 细数Qt开发的各种坑(欢迎围观)

    1:Qt的版本多到你数都数不清,多到你开始怀疑人生.从4.6开始到5.8,从MSVC编译器到MINGW编译器,从32位到64位,从Windows到Linux到MAC.MSVC版本还必须安装对应的VS2 ...

  5. STL非变易算法 - STL算法

    欢迎访问我的新博客:http://www.milkcu.com/blog/ 原文地址:http://www.milkcu.com/blog/archives/1394600460.html 原创:ST ...

  6. 迄今最安全的MySQL?细数5.7那些惊艳与鸡肋的新特性(上)【转载】

    转自: DBAplus社群 http://www.toutiao.com/m5762164771/ 迄今最安全的MySQL?细数5.7那些惊艳与鸡肋的新特性(上) - 今日头条(TouTiao.com ...

  7. 细数Python Flask微信公众号开发中遇到的那些坑

    最近两三个月的时间,断断续续边学边做完成了一个微信公众号页面的开发工作.这是一个快递系统,主要功能有用户管理.寄收件地址管理.用户下单,订单管理,订单查询及一些宣传页面等.本文主要细数下开发过程中遇到 ...

  8. 细数AutoLayout以来UIView和UIViewController新增的相关API

    本文转载至 http://www.itjhwd.com/autolayout-uiview-uiviewcontroller-api/ 细数AutoLayout以来UIView和UIViewContr ...

  9. 细数MQ那些不得不说的8大好处

    消息队列(MQ)是目前系统架构中主流方式,在大型系统及大数据中广泛采用.对任何架构或应用来说, MQ都是一个至关重要的组件.今天我们就来细数MQ那些不得不说的好处. 好处一:解耦 在项目启动之初来预测 ...

随机推荐

  1. struts2中方法拦截器(Interceptor)的中的excludeMethods与includeMethods的理解

    http://www.cnblogs.com/langtianya/archive/2013/04/10/3012205.html

  2. 提供他人class文件

    1.考虑的问题,提供的文件是否依赖于其他jar包. 例如:解析html简历时,依赖于Jsoup包.

  3. UITapGestureRecognizer会屏蔽掉Button的点击事件( 转载)

    UITapGestureRecognis 前几天在做项目的时候,遇到这个一个问题,在一个视图也就是UIView上添加一个手势,然后又在这个View上添加一个UIButton,然后给按钮添加事件,运行项 ...

  4. Servlet(三)

    重定向 服务器向浏览器发送一个302状态码以及一个Location消息头(该消息头的值是一个地址,称之为重定向地址),浏览器收到后会立即向重定向的地址发出请求,使用相应对象的API方法实现(respo ...

  5. Perl数组: shift, unshift, push, pop

    pop pop函数会删除并返回数组的最后一个元素. .. ; $fred = pop(@array); # $fred变成9,@array 现在是(5,6,7,8) $barney = pop @ar ...

  6. excel poi 文件导出,支持多sheet、多列自动合并。

    参考博客: http://www.oschina.net/code/snippet_565430_15074 增加了多sheet,多列的自动合并. 修改了部分过时方法和导出逻辑. 优化了标题,导出信息 ...

  7. [开源]jquery-ajax-cache:快速优化页面ajax请求,使用localStorage缓存请求

    项目:jquery-ajax-cache 地址:https://github.com/WQTeam/jquery-ajax-cache     最近在项目中用到了本地缓存localStorage做数据 ...

  8. Eclipse中修改Maven Repository

    1. 下载最新的Maven,解压到目录下 Maven下载地址: http://maven.apache.org/download.cgi 2. 修改config/settings.xml文件,在loc ...

  9. Day8 面向对象(补充)

    私有字段 class Foo: def __init__(self, name): self.__name = name def f1(self): print(self.__name) class ...

  10. 【译】iOS人性化界面指南(iOS Human Interface Guidelines)(一)

    1. 引言1.1 译者自述 我是一个表达能力一般的开发员,不管是书面表达,还是语言表达.在很早以前其实就有通过写博客锻炼这方面能力的想法,但水平有限实在没有什么拿得出手的东西分享.自2015年7月以来 ...