C++标准模板库(STL)之Priority_Queue

1、Priority_Queue的常用用法

priority_queue:优先队列,底层是使用堆来实现的。优先队列中,队首元素一定是当前队列中优先级最高的哪一个。

a (优先级3),b(优先级4),c(优先级1),出队顺序是:b(4)-》a(3)-》c(1)

1.1、priority_queue的定义

使用优先队列,要加头文件#include<queue>和using namespace std;

priority_queue<typename> pq;

1.2、priority_queue容器元素访问

优先队列和队列queu不一样,没有front()和back()函数,只能通过top()函数访问队首元素(堆顶元素),优先级最高的元素。

C++标准模板库(STL)之Priority_Queue

#include<stdio.h>
#include<queue>

using namespace std;

int main()
{
    priority_queue<int> q;
    q.push(3);
    q.push(4);
    q.push(1);
    printf("%dn",q.top());//输出结果为4
    return 0;
}

View Code

1.3、priority_queue的常用函数

1.3.1、push()

push(x):将x入队,时间复杂度为O(logN),N为优先队列中元素个数。

1.3.2、top()

top():获得堆顶元素,时间复杂度为O(1)

1.3.3、pop()

pop():让堆顶元素出队,时间复杂度为O(logN)

1.3.4、empty()

empty():检测优先队列是否为空,返回bool值,true为空,false非空

1.3.5、size()

size():返回优先队列中的元素个数。

1.4、priority_queue内元素优先级的设置

1.4.1、基本数据类型的优先级设置

基本数据类型:int,double,char等。

priority_queue<int> pq;
priority_queue<int,vector<int>,less<int>> pq;
/*
vector<int>:承载底层数据结构堆Heap的容器
如果第一个参数是double,那么第二个也对应是double
less<int>:是对第一个参数的比较类,less<int>表示的数组大的优先级越大。
greater<int>:表示数字小的优先级越大

priority_queue<int,vector<int>,greater<int>> pq;
//优先队列总是把最小的元素放在队首。

priority_queueK<int,vector<int>,less<int>> pq;
//优先队列总是把最大的元素放在队首。
#include<stdio.h>
#include<queue>

using namespace std;

int main()
{
    //用greater优先队列总是把最小的排在堆顶
    priority_queue<int,vector<int>,greater<int>> q;
    q.push(3);
    q.push(4);
    q.push(1);
    printf("%dn",q.top());//输出结果为1
    //用less优先队列总是把最大的排在堆顶
    priority_queue<int,vector<int>,less<int>> pq;
    pq.push(3);
    pq.push(5);
    pq.push(2);
    printf("%dn",pq.top());//输出结果为5
    return 0;
}
1.4.2、结构体的优先级设置
#include<stdio.h>
#include<queue>

using namespace std;
struct fruit
{
    string name;
    int price;
    friend bool operator < (fruit f1,fruit f2)
    {
        return f1.price<f2.price;
    }
}f1,f2,f3;

int main()
{
    priority_queue<fruit> q;
    f1.name="apple";
    f1.price=3;
    f2.name="perl";
    f2.name=4;
    f3.name="banana";
    f3.price=1;
    q.push(f1);
    q.push(f2);
    q.push(f3);
    cout<<q.top.name<<" "<<q.top().prince<<endl;//banana 1
    return 0;
}

1.5、priority_queue的常见用途

可以解决贪心问题,也可以定义Dijkstra算法进行优化

使用top()函数,必须使用empty()判断优先队列是否为空。

 

 

 

2018-09-25 20:14:03

@author:Foreordination

原文链接: https://www.cnblogs.com/drq1/p/9699514.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++标准模板库(STL)之Priority_Queue

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/281862

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 上午5:59
下一篇 2023年2月15日 上午6:00

相关推荐