priority_queue

priority_queue

今天的算法题没有遇到比较难的,所以今天就不总结算法题目了。
今天总结一个用堆实现的priority_queue,蛮好的。


priority_queue的声明模板很简单:priority_queue<Type, Container, Functional>。Type是数据类型(int,float。。),Container是容器必须是用数组实现的容器,比如 vector, deque 但不能用 list。最后一个是比较函数。STL里面容器默认用的是 vector. 比较方式默认operator< , 所以如果你把后面俩个参数缺省的话,优先队列就是大顶堆,队头元素最大。

#include <iostream>
#include <queue>

using namespace std;

int main(){
    priority_queue<int> pq;
    
    for( int i= 0; i< 10; ++i ) pq.push( i );
    while( !pq.empty() ){
        cout << pq.top() << endl;
        pq.pop();
    }
    
    getchar();
    return 0;
}

如果要使用小顶堆那么根据C++规则,三个参数都要写。STL里面定义了一个仿函数 greater<>,对于基本类型可以用这个仿函数声明小顶堆

#include <iostream>
#include <queue>

using namespace std;

int main(){
    priority_queue<int, vector<int>, greater<int> > pq;
    
    for( int i= 0; i< 10; ++i ) pq.push( i );
    while( !pq.empty() ){
        cout << pq.top() << endl;//0,1,2,3....
        pq.pop();
    }
    
    getchar();
    return 0;
}

在升级一下就是自定义类型,必须自己重载 operator< 或者自己写仿函数

#include <iostream>
#include <queue>

using namespace std;

struct mNode{//定义数据类型
    int x, y;
    Node( int a= 0, int b= 0 ):
        x(a), y(b) {}
};

bool operator<( mNodea, mNodeb ){//重载<
    if( a.x== b.x ) return a.y> b.y;
    return a.x> b.x; 
}

int main(){
    priority_queue<mNode> pq;
    
    for( int i= 0; i< 10; ++i )
    pq.push( mNode( rand(), i) );
    
    while( !pq.empty() ){
        cout << pq.top().x << ' ' << pq.top().y << endl;
        pq.pop();
    }
    
    getchar();
    return 0;
}

此时可以只带一个参数声明变量,但是不可以使用类似greater进行声明,(因为没定义呀)。那怎么定义呢?

#include <iostream>
#include <queue>

using namespace std;

struct mNode{
    int x, y;
    Node( int a= 0, int b= 0 ):
        x(a), y(b) {}
};

struct cmp{
    bool operator() ( mNode a, mNode b ){
        if( a.x== b.x ) return a.y> b.y;
        
        return a.x> b.x; }
};

int main(){
    priority_queue<mNode, vector<mNode>, cmp> pq;
    
    for( int i= 0; i< 10; ++i )
    pq.push( mNode( rand(), rand() ) );
    
    while( !pq.empty() ){
        cout << pq.top().x << ' ' << pq.top().y << endl;
        pq.pop();
    }
    
    getchar();
    return 0;
}

本文参考了好几个博客,在此列出12

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值