How to Check if a List is Empty in C++?
In C++, a list is a sequence container that allows non-contiguous memory allocation and is implemented using a doubly linked list. In this article, we will learn how to check if a list is empty in C++.
Example:
Input: myList = {1, 2, 3}; Output: List is not empty.
Check if a List is Empty in C++
To check if a std::list is empty or not, we can use the std::list::empty() function that returns true if the list is empty and returns false if the list is not empty.
C++ Program to Check if a List is Empty
The below example demonstrates how we can use the empty() function to check if the given list is empty or not in C++ STL.
// C++ Program to illustrate how to check if a list is empty
#include <iostream>
#include <list>
using namespace std;
int main()
{
// Initialize a list
list<int> myList = { 1, 2, 3 };
// Check if the list is empty
bool isEmpty = myList.empty();
// Print the result
if (isEmpty) {
cout << "List is empty" << endl;
}
else {
cout << "List is not empty" << endl;
}
return 0;
}
Output
List is not empty
Time Complexity: O(1)
Auxiliary Space: O(1)
Note: We can also use std::list::size() function to check if the given list is empty or not in C++.
Contact Us