std::queue is a container adapter that follows the First In First Out (FIFO) principle. The empty() and size() member functions are used to check whether a queue contains elements and to determine the number of elements currently stored in the queue.
- empty() checks whether the queue contains any elements.
- size() returns the current number of elements in the queue.
queue::empty()
The empty() function is used to determine whether a queue is empty.
- Returns true if the queue contains no elements.
- Returns false if the queue contains one or more elements.
- Commonly used as the loop condition while processing a queue.
Syntax
queue_name.empty();
Parameters: This function does not take any parameters.
Return Value: Returns a boolean value:
- true if the queue is empty.
- false otherwise.
#include <iostream>
#include <queue>
using namespace std;
int main()
{
queue<int> q;
q.push(1);
if (q.empty())
cout << "Queue is empty";
else
cout << "Queue is not empty";
return 0;
}
Output
Queue is not empty
queue::size()
The size() function returns the number of elements currently present in the queue.
- Returns the total number of elements in the queue.
- Does not modify the queue.
- Can be used to determine the current length of the queue.
Syntax
queue_name.size();
Parameters: This function does not take any parameters.
Return Value: Returns the number of elements present in the queue.
#include <iostream>
#include <queue>
using namespace std;
int main()
{
queue<int> q;
q.push(1);
q.push(8);
q.push(3);
q.push(6);
q.push(2);
cout << q.size();
return 0;
}
Output
5
Example: Processing a Queue Using empty()
The empty() function is commonly used while traversing and processing all elements of a queue.
#include <iostream>
#include <queue>
using namespace std;
int main()
{
queue<int> q;
q.push(1);
q.push(8);
q.push(3);
q.push(6);
q.push(2);
int sum = 0;
while (!q.empty()) {
sum += q.front();
q.pop();
}
cout << sum;
return 0;
}
Output
20
Explanation: The queue is processed until it becomes empty. During each iteration, the front element is added to the sum and then removed from the queue.
Difference Between queue::empty() and queue::size()
| Feature | queue::empty() | queue::size() |
|---|---|---|
| Purpose | Checks whether the queue is empty | Returns the number of elements |
| Return Type | bool | size_type |
| Parameters | None | None |
| Modifies Queue | No | No |
| Time Complexity | O(1) | O(1) |
Key Points to Remember
- empty() returns a boolean value indicating whether the queue contains any elements.
- size() returns the current number of elements stored in the queue.
- Both operations execute in constant time, i.e., O(1).
- empty() is generally preferred over size() == 0 when checking whether a queue is empty.