How to Check if a Deque is Empty in C++?
In C++, a deque is a container provided by the STL library that is similar to a queue. However, unlike queues, it allows insertion and deletion from both ends. In this article, we will learn how to determine whether a deque is empty or not in C++.
Example:
Input: myDeque = {2, 4, 6 } Output: dq1 is not Empty.
Checking Whether a Deque is Empty in C++
To check if a std::deque is empty or not in C++, we can use the std::deque::empty() member function which returns a boolean value true if the deque is empty and false if the deque is not empty.
Syntax of std::deque::empty()
dq_name.empty()
C++ Program to Check if a Deque is Empty
The below program demonstrates how we can check if a deque is empty or not in C++.
// C++ Program to demonstrates how we can check if a deque
// is empty or not
#include <deque>
#include <iostream>
using namespace std;
int main()
{
// Initialize a deque with few elements
deque<int> dq = { 1, 2, 3 };
// Check if deque is empty
if (dq.empty()) {
cout << "Deque is empty" << endl;
}
else {
cout << "Deque is not empty" << endl;
}
// Delete elements from the deque
dq.pop_back();
dq.pop_back();
dq.pop_back();
// Now check if a deque is empty or not
cout << "After Removal: ";
if (dq.empty()) {
cout << "Deque is empty" << endl;
}
else {
cout << "Deque is not empty" << endl;
}
return 0;
}
Output
Deque is not empty After Removal: Deque is empty
Time Complexity: O(1)
Auxiliary Space: O(1)
Contact Us