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).
SyntaxFollowing is the syntax for std::queue::empty() function.
bool empty() const;Parameters
It does not accepts any parameters.
Return valueThis function returns true if queue is empty otherwise false.
ExampleIn 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 FALSEExample
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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4