優先隊列是一種容器適配器,經過專門設計,使得隊列中的第一個元素在隊列中所有元素中最大。
priority_queue::push()
push()函數用於在優先級隊列中插入元素。將該元素添加到優先級隊列容器中,並且隊列的大小增加1。首先,將該元素添加到後麵,同時優先級隊列的元素根據優先級對其自身進行重新排序。
用法:
pqueuename.push(value) 參數: The value of the element to be inserted is passed as the parameter. Result: Adds an element of value same as that of the parameter passed in the priority queue.
例子:
Input: pqueue myqueue.push(6); Output:6 Input: pqueue = 5, 2, 1 pqueue.push(3); Output: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
priority_queue::pop()
pop()函數用於刪除優先級隊列的頂部元素。
用法:
pqueuename.pop() 參數: No parameters are passed. Result: The top element of the priority queue is removed.
例子:
Input: pqueue = 3, 2, 1 myqueue.pop(); Output:2, 1 Input: pqueue = 5, 3, 2, 1 pqueue.pop(); Output: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函數的情況下找到優先級隊列的大小。
Input:5, 13, 0, 9, 4 Output: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
相關用法
注:本文由純淨天空篩選整理自AyushSaxena大神的英文原創作品 priority_queue::push() and priority_queue::pop() in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。