STL优先队列模板

1. 优先队列

用途:按照某一个关键字对插入元素或删除元素后的数据集进行自动排序

复杂度: logN

2. 数据声明

(1)头文件:#include<queue>

(2)声明:  priority_queue <T> q; //T是一个泛型,可以是结构体

       priority_queue <T,vector<T>,greater<T> > q;

  greater函数也可以通过对结构体重载一个<运算符的bool函数

3. 库函数

q.size();//返回q里元素个数
q.empty();//返回q是否为空,空则返回1,否则返回0
q.push(k);//在q的末尾插入k
q.pop();//删掉q的第一个元素
q.top();//返回q的第一个元素
q.back();//返回q的末尾元素

 

4. 实例

#include <iostream>
#include <queue> 
using namespace std;
struct Node{
    int x, y;
    Node(int a=0, int b=0):
        x(a),y(b){}
};
bool operator<(Node a, Node b){//返回true时,说明a的优先级低于b
    //x值较大的Node优先级低(x小的Node排在队前)
    //x相等时,y大的优先级低(y小的Node排在队前)
    if( a.x== b.x ) return a.y> b.y;
    return a.x> b.x; 
}
int main(){
    priority_queue<Node> q;
    for( int i= 0; i< 10; ++i )
    q.push( Node( rand(), rand() ) );
    while( !q.empty() ){
        cout << q.top().x << ' ' << q.top().y << endl;
        q.pop();
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/czsharecode/p/10502281.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值