zoukankan      html  css  js  c++  java
  • priority_queue的用法

    priority_queue本质是一个堆,默认为按照元素值的大小从大到小排序

    1.简单的使用方法

    //二叉树  默认为小根堆
    #include<iostream>
    #include<queue>
    using namespace std;
    int main()
    {
        priority_queue<int>  pq;
        pq.push(1);
        cout<<pq.size()<<endl;
        while(pq.empty()){
            cout<<pq.top()<<" ";
            pq.pop();
        }
        cout<<endl;
    } 
    View Code

    默认状态:

    #include<iostream>
    #include<queue>
    using namespace std;
     
    int main(){
        priority_queue<int> p;
        p.push(1);
        p.push(2);
        p.push(8);
        p.push(5);
        p.push(43);
        for(int i=0;i<5;i++){
            cout<<p.top()<<endl;
            p.pop();
        }
        return 0;
    }
    View Code

    优先输出小数据:

    priority_queue<int, vector<int>, greater<int> > p;

    #include<iostream>
    #include<queue>
    using namespace std;
     
    int main(){
        priority_queue<int, vector<int>, greater<int> >p;
        p.push(1);
        p.push(2);
        p.push(8);
        p.push(5);
        p.push(43);
        for(int i=0;i<5;i++){
            cout<<p.top()<<endl;
            p.pop();
        }
        return 0;
    }
    View Code

    2.重载  “<”  定义优先级

    #include<iostream>
    #include<queue>
    #include<cstdlib>
    using namespace std;
    struct Node{
        int x,y;
        Node(int a=0, int b=0):
            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>p;
        
        for(int i=0; i<10; ++i)
            p.push(Node(rand(), rand()));
            
        while(!p.empty()){
            cout<<p.top().x<<' '<<p.top().y<<endl;
            p.pop();
        }//while
        //getchar();
        return 0;
    }
    View Code
  • 相关阅读:
    Func<T>、Action<T> 的区别于说明
    Invoke()/BeginInvoke()区别
    C# Linq处理list数据
    C# 的三种序列化方法
    P3368 【模板】树状数组 2
    P2058 海港
    2019.6.24 校内测试 NOIP模拟 Day 2 分析+题解
    2019.6.20 校内测试 NOIP模拟 Day 1 分析+题解
    2019.6.18 校内测试 分析+题解
    P1310 表达式的值
  • 原文地址:https://www.cnblogs.com/helloworld2019/p/10366298.html
Copyright © 2011-2022 走看看