priority_queue::push() and priority_queue::pop() in C++ STL (original) (raw)

Last Updated : 24 Oct, 2024

In C++, **priority_queue::push() and **priority_queue::pop() methods are used to insert and delete the element from the priority_queue container. They both are the member functions of std::priority_queue class defined inside ****** header file. In this article, we will learn about priority_queue::push() and priority_queue::pop() methods in C++.

**Example:

C++ `

// C++ Program to demonstrate use of priority_queue // push() and pop() methods #include <bits/stdc++.h> using namespace std;

int main() { priority_queue pq; pq.push(10); pq.push(30); pq.push(20);

while(!pq.empty()) {
  cout << pq.top() << " ";
  pq.pop();
}
return 0;

}

`

priority_queue::push() Method

The std::priority_queue::push() method is used to insert (or push) an element in the std::priority queue. As priority queue implements heap data structure, this function inserts the element at the back for queue and then use the heapify up algorithm to maintain the heap property.

**Syntax

pq.**push(_val);

**Parameters

**Return Value

priority_queue::pop() Method

The priority_queue::pop() function is used to delete (or pop) the top element i.e. the element with highest priority from the priority queue. This function ensures that the heap property is maintained after the deletion of the top element.

**Syntax

pq.**pop()_;

**Parameters

**Return Value

More Examples of priority_queue push() and pop()

The push() and pop() methods are the primary methods for insertion and deletion of elements in priority_queue container. The below example demonstrates the use of these functions:

Example 1: push() and pop() for Min Heap Priority Queue

By default, priority queue uses max heap, but we can change this using custom comparator function. Let's see the working of push and pop in min heap priority queue.

C++ `

// C++ program to use push() and pop() method // with min heap priority queue #include <bits/stdc++.h> using namespace std;

int main() { priority_queue<int, vector, greater> pq;

// Pushing elements
pq.push(10);
pq.push(30);
pq.push(20);

// Printing current top element
cout << pq.top() << endl;

// Popping the top element
pq.pop();

// Printing current top element
cout << pq.top();
return 0;

}

`

Example 2: Trying pop() Method with Empty Priority Queue

C++ `

// C++ Program to demonstrate use of priority_queue // push() and pop() methods #include <bits/stdc++.h> using namespace std;

int main() { priority_queue pq; pq.pop(); return 0; }

`

**Output

_(no output)

**Explanation: The behaviour of pop() method is undefined for empty priority queue so; it is always recommended to check whether the queue is empty or not before using pop() method.