STL——优先队列priority_queue 的用法

要包含头文件#include<queue>

priority_queue< type, container, function>
type :类型
container:实现优先队列的底层容器(可缺省)
function:元素之间的比较方式(可缺省)

对于container,要求必须是数组形式实现的容器,例如vector、deque,而不能使list。
在STL中,默认情况下(不加后面两个参数)是以vector为容器,以 operator< 为比较方式,所以在只使用第一个参数时,优先队列默认是一个最大堆,每次输出的堆顶元素是此时堆中的最大元素。

//升序队列
priority_queue<int,vector<int>,greater<int>>  q;
//降序队列
priority_queue<int,vector<int>,less<int>>  q;

队列是先进先出,那么优先队列则不一样了,进的顺序不能决定出的顺序,优先队列出的顺序是按照自己设置的优先等级来出队列的,如果自己不设置优先级的话,默认优先级为越大优先级越高。

下面是代码解释以及实现:

#include<iostream>
//优先队列要包含这个头文件
#include<queue>
#include<functional>
using namespace std;

void test01(){
    //对于基础类型,默认是大顶堆
    priority_queue<int> a;
    //等同于 priority_queue<int, vector<int>, less<int> > a;
    for(int i=0;i<5;i++){
        a.push(i);
    }
    while(!a.empty()){
        cout<<a.top()<<' ';
        a.pop();
    }
    cout<<endl;
    cout<<endl;
}

void test02(){
    //这样就是小顶堆
    priority_queue<int,vector<int>,greater<>> b;
    for(int i=0;i<5;i++){
        b.push(i);
    }
    while(!b.empty()){
        cout<<b.top()<<' ';
        b.pop();
    }
    cout<<endl;
    cout<<endl;
}

void test03(){
    //字符串的比较
    priority_queue<string> c;
    c.push("abc");
    c.push("abcd");
    c.push("cbd");
    while(!c.empty()){
        cout<<c.top()<<' ';
        c.pop();
    }
    cout<<endl;
    cout<<endl;
}

void test04(){
    //pari的比较,先比较第一个元素,第一个相等比较第二个
    priority_queue<pair<int, int>> a;
    pair<int,int> b(1, 2);
    pair<int,int> c(1, 3);
    pair<int,int> d(2, 5);
    a.push(d);
    a.push(c);
    a.push(b);
    while(!a.empty()){
        cout<<a.top().first<<' '<<a.top().second<<'\n';
        a.pop();
    }
    cout<<endl;
}

//自定义的类型
struct MyType{
    int val;
    MyType(int a){val = a;}
    //运算符重载<
    bool operator<(const MyType& a)const{
        return val<a.val; //大顶堆
    }
};

void test05(){
    MyType a(1);
    MyType b(2);
    MyType c(3);
    priority_queue<MyType> d;
    d.push(b);
    d.push(c);
    d.push(a);
    while(!d.empty()){
        cout<<d.top().val<<' ';
        d.pop();
    }
    cout<<endl;
    cout<<endl;
}

struct MyType02{
    //重写仿函数
    bool operator()(MyType a, MyType b){
        return a.val>b.val; //小顶堆
    }
};

void test06(){
    MyType a(1);
    MyType b(2);
    MyType c(3);
    priority_queue<MyType, vector<MyType>, MyType02> f;
    f.push(c);
    f.push(b);
    f.push(a);
    while (!f.empty()){
        cout<<f.top().val<<' ';
        f.pop();
    }
    cout<<endl;
    cout<<endl;
}

int main(){
    test01();
    test02();
    test03();
    test04();
    //05、06是自定义类型的比较
    test05();
    test06();
    return 0;
}

我是花花,祝自己也祝您变强了~ 

Guess you like

Origin blog.csdn.net/m0_52711790/article/details/120966523