C++ STL 中的 priority_queue::push() 和 priority_queue::pop()

        优先级队列是一种容器适配器,经过专门设计,队列的第一个元素要么是队列中所有元素中最大的,要么是最小的。然而,在 C++ STL 中(默认情况下),最大的元素位于顶部。我们还可以创建一个优先级队列,在创建优先级队列时只需传递一个额外的参数,将最小的元素放在顶部。

优先级队列::push()

        push() 函数用于在优先级队列中插入一个元素。该元素被添加到优先级队列容器中,队列的大小增加 1。首先,将元素添加到后面,同时优先级队列的元素根据优先级重新排序。 

时间复杂度:O(log n)
语法 :

pqueuename.push(value)
参数:
要插入的元素的值作为参数传递。
结果 :
添加与以下元素值相同的元素
优先级队列中传递的参数。

例子:
输入:pqueue 
         pqueue.push(6);
输出:6

输入:pqueue = 5, 2, 1 
         pqueue.push(3);
输出:5, 3, 2, 1

错误和异常
1. 如果传递的值与优先级队列类型不匹配,则显示错误。 
2. 如果参数不引发任何异常,则显示无异常引发保证。 

// CPP program to illustrate
// Implementation of push() function
#include <iostream>
#include <queue>
using namespace std;
 
int main()
{
    // Empty Queue
    priority_queue<int> pqueue;
    pqueue.push(3);
    pqueue.push(5);
    pqueue.push(1);
    pqueue.push(2);
    // Priority queue becomes 5, 3, 2, 1
 
    // Printing content of queue
    while (!pqueue.empty()) {
        cout << ' ' << pqueue.top();
        pqueue.pop();
    }
}

输出:

5 3 2 1

优先级队列::pop()

pop() 函数用于删除优先级队列的顶部元素。 

时间复杂度:O(log n)
语法 :

pqueuename.pop()
参数:
不传递任何参数。

结果:
移除
优先级队列的顶部元素

例子:

输入:pqueue = 3, 2, 1 
         myqueue.pop();
输出:2, 1

输入:pqueue = 5, 3, 2, 1 
         pqueue.pop();
输出:3, 2, 1

错误和异常
1. 如果传递了参数,则显示错误。 
2. 如果参数没有引发任何异常,则显示无异常引发保证。

// CPP program to illustrate
// Implementation of pop() function
#include <iostream>
#include <queue>
using namespace std;
 
int main()
{
    // Empty Priority Queue
    priority_queue<int> pqueue;
    pqueue.push(0);
    pqueue.push(1);
    pqueue.push(2);
    // queue becomes 2, 1, 0
 
    pqueue.pop();
    pqueue.pop();
    // queue becomes 0
 
    // Printing content of priority queue
    while (!pqueue.empty()) {
        cout << ' ' << pqueue.top();
        pqueue.pop();
    }
}


输出:

0

        应用:push() 和 pop()给定一些整数,将它们添加到优先级队列,并在不使用 size 函数的情况下找到优先级队列的大小。

输入:5、13、0、9、4
输出:5

算法
1. 将给定元素逐个推送到优先级队列容器中。 
2. 不断弹出优先级队列的元素,直到队列为空,并增加计数器变量。 
3. 打印计数器变量。

// CPP program to illustrate
// Application of push() and pop() function
#include <iostream>
#include <queue>
using namespace std;
 
int main()
{
    int c = 0;
    // Empty Priority Queue
    priority_queue<int> pqueue;
    pqueue.push(5);
    pqueue.push(13);
    pqueue.push(0);
    pqueue.push(9);
    pqueue.push(4);
    // Priority queue becomes 13, 9, 5, 4, 0
 
    // Counting number of elements in queue
    while (!pqueue.empty()) {
        pqueue.pop();
        c++;
    }
    cout << c;
}

输出:

5

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值