C++ priority_queue::empty() Function



The C++ std::priority_queue::empty() function of the priority_queue is used to check whether is queue is empty or not. It returns a boolean value true if the queue contains no elements otherwise false. It is useful for executing the code when the queue is not empty, preventing the errors from trying to access elements in an empty queue. The time complexity of this function is constant i.e.O(1).

Syntax

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

bool empty() const;

Parameters

This function does not accept any parameter.

Return value

This function returns true if priority_queue is empty otherwise false.

Example

Let's look at the following example, where we are going to check whether the priority_queue is empty or not.

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

Output

Following is the output of the above code −

Priority_queue is empty.

Example

Consider the following example, where we are going to push the elements into the priority_queue and then use a loop to print and remove elements until it gets empty.

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

Output

Output of the above code is as follows −

2 1 

Example

In the following example, we are going to use the empty() function and going to check whether the priority_queue is empty or not.

#include <iostream>
#include <queue>
#include <string>
int main()
{
    std::priority_queue<std::string> a;
    a.push("Welcom");
    a.push("TP");
    if (a.empty()) {
        std::cout << "Priority_queue is empty." << std::endl;
    } else {
        std::cout << "Priority_queue is not empty." << std::endl;
    }
    return 0;
}

Output

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

Priority_queue is not empty.
priority_queue.htm
Advertisements