The following table shows commonly used priority queue APIs:
|
API |
Description |
|
push() |
This appends a new value at the back of the priority queue |
|
pop() |
This removes the value at the front of the priority queue |
|
empty() |
This returns true when the priority queue is empty; otherwise it returns false |
|
size() |
This returns the number of values stored in the priority queue |
|
top() |
This returns the value in the front of the priority queue |
Let's write a simple program to understand priority_queue:
#include <iostream>
#include <queue>
#include <iterator>
#include <algorithm>
using namespace std;
int main () {
priority_queue<int> q;
q.push( 100 );
q.push( 50 );
q.push( 1000 );
q.push( 800 );
q.push( 300 );
cout << "nSequence in which value are inserted are ..." << endl;
cout << "100t50t1000t800t300" << endl;
cout << "Priority queue values are ..." << endl;
while ( ! q.empty() ) {
cout << q.top() << "t";
q.pop();
}
cout << endl;
return 0;
}
The program can be compiled and the output can be viewed with the following command:
g++ main.cpp -std=c++17
./a.out
The output of the program is as follows:
Sequence in which value are inserted are ...
100 50 1000 800 300
Priority queue values are ...
1000 800 300 100 50
From the preceding output, you can observe that priority_queue is a special type of queue that reorders the inputs in such a way that the highest value appears first.