Home »
C++ STL
std::list::empty() function in C++ STL
C++ STL: std::list::empty() function with example: In this tutorial, we will learn to check whether a list is empty or not using list::empty() function.
Submitted by IncludeHelp, on July 02, 2018
C++ STL - std::list::empty() function
empty() is the function of list class, it is used to check whether a list container is empty or not, it returns true (integer value: 1) if list container is empty i.e. its size is 0, otherwise function return false (integer value: 0).
Syntax
list::empty(void);
Parameter(s)
No parameter is passed to the function
Return value
- True (1), if list container is empty
- False (0), if list container is not empty
Sample Input and Output
Input: list list1 {10, 20, 30, 40, 50}
Function calling/validation: list1.empty();
Output: False
Input: list list1 {}
Function calling/validation: list1.empty();
Output: True
Example 1
In this example, there are two lists, list1 has 5 elements and list2 has 0 elements. We have to check whether list containers are empty or not?
#include <iostream>
#include <list>
using namespace std;
int main() {
// declare and initialize lists
list<int> list1{10, 20, 30, 40, 50};
list<int> list2;
// check list1 is empty or not
if (list1.empty())
cout << "list1 is an empty list\n";
else
cout << "list1 is not an empty list\n";
// check list2 is empty or not
if (list2.empty())
cout << "list2 is an empty list\n";
else
cout << "list2 is not an empty list\n";
return 0;
}
Output
list1 is not an empty list
list2 is an empty list
Example 2
In this example, there is one list with 5 elements, we have to print its elements by checking till list is not empty i.e. we have to print all elements, and also check if list is empty then returns false.
#include <iostream>
#include <list>
using namespace std;
int main() {
// declaring list
list<int> list1{10, 20, 30, 40, 50};
// printing the elements, if list1 is not empty
if (!(list1.empty())) {
cout << "List's elements are:\n";
while (!(list1.empty())) {
cout << list1.front() << endl;
list1.pop_front();
}
} else
cout << "list is empty!!!\n";
return 0;
}
Output
List's elements are:
10
20
30
40
50