How to Delete an Element from a Priority Queue in C++ ?
Last Updated :
07 Feb, 2024
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++
#include <iostream>
#include <queue>
using namespace std;
int main()
{
priority_queue< int > pq;
pq.push(10);
pq.push(30);
pq.push(20);
pq.push(50);
cout << "Top element before removal: " << pq.top()
<< endl;
pq.pop();
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)
Share your thoughts in the comments
Please Login to comment...