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

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: No parameter is passed to the function

Return type:

  • True (1), if list container is empty
  • False (0), if list container is not empty

Example:

    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
Advertisement

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

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.