C++ priority_queue::pop() Function



The C++ std::priority_queue::pop() function is used to remove the top priority element from the queue. It does not return any value but modifies the queue in place and decreases the size of the priority_queue by one. The time complexity of this function is constant i.e.O(1).

When we try to invoke the pop() function on the empty priority_queue, it results in undefined behaviour.

Syntax

Following is the syntax for std::priority_queue::pop() function.

void pop();

Parameters

This function does not accepts any parameter

Return value

This function does not return any value.

Example

Let's look at the following example, where we are going to demonstrate the usage of pop() function.

#include <iostream>
#include <queue>
int main()
{
    std::priority_queue<int> x;
    x.push(1);
    x.push(22);
    x.push(333);
    std::cout << "Before popping top element : " << x.top() << std::endl;
    x.pop();
    std::cout << "After popping top element: " << x.top() << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

Before popping top element : 333
After popping top element: 22

Example

Consider the following example, where we are going to pop all the elements in the priority_queue.

#include <iostream>
#include <queue>
int main()
{
    std::priority_queue<int> a;
    a.push(1);
    a.push(22);
    a.push(333);
    std::cout << "Elements in the priority_queue:" << std::endl;
    while (!a.empty()) {
        std::cout << a.top() << " ";
        a.pop();
    }
    std::cout << std::endl;
    return 0;
}

Output

If we run the above code it will generate the following output −

Elements in the priority_queue:
333 22 1 

Example

In the following eample, we are going to demonstrate how to handle the case when the priority_queue is empty.

#include <iostream>
#include <queue>
int main()
{
    std::priority_queue<int> a;
    if (!a.empty()) {
        std::cout << "Before popping top element: " << a.top() << std::endl;
        a.pop();
    } else {
        std::cout << "Priority_queue is empty." << std::endl;
    }
    return 0;
}

Output

Let us compile and run the above program, this will produce the following result −

Priority_queue is empty.
priority_queue.htm
Advertisements