C++ Check if the Queue is Empty
In C++, you can check if a queue is empty using the empty()
method. Here's an example:
#include <iostream> #include <queue> using namespace std; int main() { queue<int> myQueue; if (myQueue.empty()) { cout << "The queue is empty." << endl; } else { cout << "The queue is not empty." << endl; } myQueue.push(10); myQueue.push(20); myQueue.push(30); if (myQueue.empty()) { cout << "The queue is empty." << endl; } else { cout << "The queue is not empty." << endl; } return 0; }Sourcewww:.theitroad.com
In the example above, we first create an empty queue called myQueue
and use the empty()
method to check if it's empty. Since it is empty, the program prints "The queue is empty."
We then add three integers to the queue using the push()
method and use the empty()
method again to check if the queue is empty. Since it now contains elements, the program prints "The queue is not empty."
The output of this program would be:
The queue is empty. The queue is not empty.
Note that the empty()
method returns a boolean value (true
if the queue is empty, false
otherwise).