zoukankan      html  css  js  c++  java
  • priority_queue优先队列

    1.定义:priority_queue<Type, Container, Functional>
    Type 就是数据类型
    Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,
    但不能用 list。STL里面默认用的是vector),
    Functional 就是比较的方式,
    当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大根堆

    2.基本函数
    q.size();//返回q里元素个数
    q.empty();//返回q是否为空,空则返回true,否则返回false
    q.push();//插入元素,并对底层容器排序
    q.pop();//删掉q的第一个元素
    q.top();//返回q的第一个元素

    3.

    priority_queue<int,vector<int>,less<int> > q;
    priority_queue<int,vector<int>,greater<int> > q;
    less优先级是栈顶元素从大到小,而greater正好与其相反。

    #include<iostream>
    #include<vector>
    #include<queue>
    using namespace std;
    int tmp[100];
    struct cmp1{
        bool operator()(int x,int y)
        {
            return x>y;//小的优先级高 ,从小到大排 
        }
    }; 
    struct cmp2{
        bool operator()(const int x,const int y)
        {
            return tmp[x]>tmp[y];
        }
    }; 
    struct node{
        int x,y;
        friend bool operator<(node a,node b)
        {
            return a.x>b.x;//按x从小到大排 
        }
    };
    priority_queue<int>q1;
    priority_queue<int,vector<int>,cmp1>q2;
    priority_queue<int,vector<int>,cmp2>q3;
    priority_queue<node>q4;
    int main()
    {
        int i,j,k,m,n;
        int x,y;
        node a;
        while(cin>>n)
        {
            for(int i=0;i<n;i++)
            {
                cin>>a.y>>a.x;
                q4.push(a);
            }
            cout<<endl;
            while(!q4.empty())
            {
                cout<<q4.top().y<<" "<<q4.top().x<<" "<<endl;
                q4.pop();
            }
            cout<<endl;
            
        int t;
            for(i=0;i<n;i++)
            {
                cin>>t;
                q2.push(t);
            }
            while(!q2.empty())
            {
                cout<<q2.top()<<endl;
                q2.pop();
            }
            cout<<endl;
        }
        return 0;
    }
    自定义排序

    参考:https://blog.csdn.net/yanyanwenmeng/article/details/78153192

  • 相关阅读:
    设计模式之桥接模式
    设计模式之适配器模式
    设计模式之代理模式
    设计模式之建造者模式
    设计模式之抽象工厂模式
    设计模式之工厂方法模式
    设计模式之简单工厂模式
    设计模式之原型模式
    api接口测试的步骤
    3种优化回归测试的方法
  • 原文地址:https://www.cnblogs.com/adelalove/p/12253168.html
Copyright © 2011-2022 走看看