How to Delete an Element from a Priority Queue in C++ ?
Last Updated :
07 Feb, 2024
Improve
In C++, a priority queue is a queue in which elements are arranged based on their priority values as each element has a priority value associated with it. In this article, we will learn how to delete an element from a priority queue in C++.
For Example,
Input: myPriorityQueue = {8, 6, 7, 5, 4, 2, 3} Output:
myPriorityQueue = {7, 6, 3, 5, 4, 2}
Remove Element from Priority Queue in C++
To remove an element from a priority_queue we can use a std::priority_queue::pop() function that directly removes the element with the highest priority (topmost element) from the queue and the element with the next highest priority becomes the top element after deletion.
C++ Program to Delete Element from Priority Queue
The below example demonstrates the deletion of an element using pop() in a priority queue.
// C++ program to delete an element from priority queue
#include <iostream>
#include <queue>
using namespace std;
int main()
{
// creating a priority queue
priority_queue<int> pq;
// push element in a priority queue
pq.push(10);
pq.push(30);
pq.push(20);
pq.push(50);
// printing the top most element before deletion
cout << "Top element before removal: " << pq.top()
<< endl;
// Remove the top element
pq.pop();
// printing the top most element after deletion
cout << "Top element after removal: " << pq.top()
<< endl;
return 0;
}
Output
Top element before removal: 50 Top element after removal: 30
Time Complexity: O(log N), where N is the number of elements in the priority queue.
Auxiliary Space: O(1)