C++ STL 中的优先级队列容器

原文:https://www.studytonight.com/cpp/stl/stl-container-priority-queue

priority_queue就像一个正常的队列,只是从队列中移除的元素总是队列中所有元素中最大的,因此这个容器通常用于在 C++ 中复制 Max Heap 。元素可以任意顺序插入,并且插入的时间复杂度为O(log(n))

以下是创建优先级队列的语法:

**priority_queue**<int> *pq*;

优先级队列的成员函数

下面是 STL 中优先级队列容器的一些常用函数:

push功能

这个方法在 priority_queue 中插入一个元素。元素的插入具有对数时间的时间复杂度。

#include <iostream>>     
#include <queue>

using namespace std;

int main ()
{
    **priority_queue**<int> pq1;

    pq1.**push**(30);  *// inserts 30 to pq1 , now top = 30*
    pq1.**push**(40);  *// inserts 40 to pq1 , now top = 40 ( maxinmum element)*
    pq1.**push**(90);  *// inserts 90 to pq1 , now top = 90* 
    pq1.**push**(60);    *// inserts 60 to pq1 , top still is 90*    

    return 0;
}

pop功能

此方法从 priority_queue(最大元素)中移除最顶端的元素,将优先级队列的大小减少 1。

#include <iostream>>     
#include <queue>

using namespace std;

int main ()
{
    **priority_queue**<int> pq1;

    pq1.**push**(30);  *// inserts 30 to pq1 , now top = 30*
    pq1.**push**(40);  *// inserts 40 to pq1 , now top = 40 ( maxinmum element)*
    pq1.**push**(90);  *// inserts 90 to pq1 , now top = 90* 
    pq1.**push**(60);    *// inserts 60 to pq1 , top still is 90*    

    pq1.**pop**();  *// removes 90 ( greatest element in the queue* 

    return 0;
}

top功能

此方法返回优先级队列顶部的元素,这是队列中最大的元素。

emptysize功能

size()返回 priority _queue 中存在的元质数量,而如果 priority_queue 为空,则empty()返回布尔值 true,否则返回布尔值 false。

swap功能

这个方法交换两个 priority_queue 的元素。