C++优先队列使用

来源:互联网 发布:spss预测后显示数据 编辑:程序博客网 时间:2024/05/22 00:08

优先队列(priority queue)
普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除。在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除。优先队列具有最高级先出 (largest-in,first-out)的行为特征。
STL中的优先队列-priorit_queue,包含在头文件”queue”中,可以使用具有默认优先级的已有数据结构;也可以再定义优先队列的时候传入自定义的优先级比较对象;或者使用自定义对象(数据结构),但是必须重载好< 操作符。

1.优先队列的常用操作

        q.empty()          如果队列为空,则返回true,否则返回false        q.size()           返回队列中元素的个数        q.pop()            删除队首元素,但不返回其值        q.top()            返回具有最高优先级的元素值,但不删除该元素        q.push(item)       在基于优先级的适当位置插入新元素
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

其中q.top()为查找操作,在最小优先队列中搜索优先权最小的元素,在最大优先队列中搜索优先权最大的元素。q.pop()为删除该元素。优先队列插入和删除元素的复杂度都是O(lgn),所以速度很快;另外,在优先队列中,元素可以具有相同的优先权。
priority_queue模板原型

template< class T ,class Sequence=vector<T> ,classCompare=less<typenameSequence::value_type> >class priority_queue;
  • 1
  • 2

2.优先队列常用定义和重载运算符方法

①默认优先级:

#include <queue>using namespace std;priority_queue<int> q; 
  • 1
  • 2
  • 3
  • 4

通过<操作符可知在整数中元素大的优先级高。

②传入一个比较函数,使用functional.h函数对象作为比较函数。

#include <queue>#include <functional>using namespace std;priority_queue<int, vector<int>, greater<int> > q;  
  • 1
  • 2
  • 3
  • 4
  • 5

此时整数中元素小的优先级高。

③传入比较结构体,自定义优先级。

#include <queue>using namespace std;struct cmp{    bool operator ()(int a,int b){    //通过传入不同类型来定义不同类型优先级        return a>b;    //最小值优先    }};/**struct cmp{    bool operator ()(int a,int b){        return a<b;    //最大值优先    }};**/priority_queue<int, vector<int>, cmp > q;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

④自定义数据结构,自定义优先级。

#include <queue>using namespace std;struct node {    int priority;    int value;    friend bool operator < (const node &a, const node &b) {          return a.priority < b.priority;    }    /* 这样写也可以    bool operator < (const node &a) const {        return priority < a.priority;    }    */};/**因为标准库默认使用元素类型的<操作符来确定它们之间的优先级关系。而且自定义类型的<操作符与>操作符并无直接联系,故会编译不过。struct node {    int priority;    int value;    friend bool operator > (const node &a, const node &b) {   //错误示范        return a.priority > b.priority;      }};**/priority_queue<node> q;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
            <link href="http://s.csdnimg.cn/static/markdown/markdown_views.css?v=2.0" rel="stylesheet">                </div>
原创粉丝点击