優先隊列是一種容器適配器,經過專門設計,使得隊列中的第一個元素在隊列中所有元素中最大。
priority_queue::top()
top()函數用於引用優先級隊列的頂部(或最大)元素。
用法:
pqueuename.top() 參數: No value is needed to pass as the parameter. 返回: Direct reference to the top(or the largest) element of the priority queue container.
例子:
Input :pqueue.push(5); pqueue.push(1); pqueue.top(); Output:5 Input :pqueue.push(5); pqueue.push(1); pqueue.push(7); pqueue.top(); Output:7
錯誤和異常
1.如果優先級隊列容器為空,則會導致未定義的行為
2.如果優先級隊列不為空,則沒有異常拋出保證
// CPP program to illustrate
// Implementation of top() function
#include <iostream>
#include <queue>
using namespace std;
int main()
{
priority_queue<int> pqueue;
pqueue.push(5);
pqueue.push(1);
pqueue.push(7);
// Priority queue top
cout << pqueue.top();
return 0;
}
輸出:
7
應用:
給定優先級整數隊列,找到質數和非質數的數量。
Input:8, 6, 3, 2, 1 Output:Prime - 2 Non Prime - 3
算法
1.在變量中輸入優先級隊列的大小。
2.檢查優先級隊列是否為空,檢查最上麵的元素是否為素數,如果prime遞增素數計數器,然後彈出頂部元素。
3.重複此步驟,直到優先級隊列為空。
4.打印變量prime和nonprime(size-prime)的最終值。
// CPP program to illustrate
// Application of top() function
#include <iostream>
#include <queue>
using namespace std;
int main()
{
int prime = 0, nonprime = 0, size;
priority_queue<int> pqueue;
pqueue.push(1);
pqueue.push(8);
pqueue.push(3);
pqueue.push(6);
pqueue.push(2);
size = pqueue.size();
// Priority queue becomes 1, 8, 3, 6, 2
while (!pqueue.empty()) {
for (int i = 2; i <= pqueue.top() / 2; ++i) {
if (pqueue.top() % i == 0) {
prime++;
break;
}
}
pqueue.pop();
}
cout << "Prime - " << prime << endl;
cout << "Non Prime - " << size - prime;
return 0;
}
輸出:
Prime - 2 Non Prime - 3
相關用法
注:本文由純淨天空篩選整理自AyushSaxena大神的英文原創作品 priority_queue::top() in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。