Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C++ Queue::empty() Function



The C++ std::queue::empty() function is used to check whether the queue is empty or not and returns a boolean value, true if the queue is empty and does not contains any elements otherwise false. This function can also be used in the conjunction with loops or conditionals. The time complexity of this function is constant O(1).

Syntax

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

bool empty() const;

Parameters

It does not accepts any parameters.

Return value

This function returns true if queue is empty otherwise false.

Example

In the following example, we are going to demonstrate the basic usage of empty() function.

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> a;
    if (a.empty()) {
        std::cout << "TRUE" << std::endl;
    }
    a.push(1);
    if (!a.empty()) {
        std::cout << "FALSE" << std::endl;
    }
    return 0;
}

Output

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

TRUE
FALSE

Example

Consider the following example, where we are going to use the empty() in a loop to process and remove elements until the queue is empty.

#include <iostream>
#include <queue>
int main() {
    std::queue<int> x;
    x.push(1);
    x.push(2);
    while (!x.empty()) {
        std::cout << " " << x.front() << std::endl;
        x.pop();
    }
    if (x.empty()) {
        std::cout << "The queue was empty now." << std::endl;
    }
    return 0;
}

Output

Following is the output of the above code −

 1
 2
The queue was empty now.

Example

Let's look at the following example, where we are going to check the state of the queue in different scenarios.

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> a;
    std::cout << "Initial stage: " << (a.empty() ? "empty" : "not empty") << std::endl;
    a.push(1);
    std::cout << "After pushing: " << (a.empty() ? "empty" : "not empty") << std::endl;
    a.pop();
    std::cout << "After popping: " << (a.empty() ? "empty" : "not empty") << std::endl;
    return 0;
}

Output

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

Initial stage: empty
After pushing: not empty
After popping: empty
queue.htm
Advertisements