优先队列

2017-07-24  22:49:57

writer:pprp

优先队列很好使用,能把一个队列中具有优先性的元素提取出来,最大或者最小

分为最小优先队列和最大优先队列;

使用在头文件#include<queue>中

struct cmp1
{  
    bool operator ()(int &a,int &b)
    {  
        return a>b;//最小值优先  
    }  
}; 
struct cmp2
{  
    bool operator ()(int &a,int &b)
    {  
        return a<b;//最大值优先  
    }  
}; 
//定义一个结构体,在结构体中通过运算符重载,自定义优先级
struct p1
{  
    int x;  
    bool operator < (const number1 &a) const
   {  
        return x>a.x;//最小值优先  
    }  
};  
struct p2
{  
    int x;  
    bool operator < (const number2 &a) const
    {  
        return x<a.x;//最大值优先  
    }  
};

在声明的时候用法:

    priority_queue<int>que;//采用默认优先级构造队列:最大值优先  
  
    priority_queue<int,vector<int>,cmp1>que1;//最小值优先  
    priority_queue<int,vector<int>,cmp2>que2;//最大值优先  
  
    priority_queue<int,vector<int>,greater<int> >que3;//最小值优先
    priority_queue<int,vector<int>,less<int> >que4;////最大值优先  
  
    priority_queue<p1>que5;  
priority_queue
<p2>que6;

内置函数:跟队列用法差不多,差距在Pop()函数,删除的是有优先性的元素;

还有top()函数,取出的是当前优先性的元素;

//优先队列为空返回真,不为空则返回假;
    bool empty();
//pop()函数删除优先队列中的第一个元素;
    void pop();
//push()函数添加一个元素到优先队列中,值为val;
    void push( const TYPE &val );
//size()函数返回优先队列中存储的元素个数;
    size_type size();
//top()返回一个引用,指向优先队列中有最高优先级的元素。注意只有pop()函数删除一个元素
     TYPE &top();
原文地址:https://www.cnblogs.com/pprp/p/7231732.html