list empty() function in C++ STL

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of list::empty() function in C++.

What is a List in STL?

List is a data structure that allows constant time insertion and deletion anywhere in sequence. Lists are implemented as doubly linked lists. Lists allow non-contiguous memory allocation. List perform better insertion extraction and moving of element in any position in container than array, vector and deque. In List the direct access to the element is slow and list is similar to forward_list, but forward list objects are single linked lists and they can only be iterated forwards.

What is list::empty()?

list::empty() is an inbuilt function in C++ STL which is declared in header file. list::empty() checks whether the given list container is empty(size is 0) or not, and returns true value if the list is empty and false if the list is not empty.

Syntax

bool list_name.empty();

This function accepts no value.

Return Value

This function returns true if the container size is zero and false if the container size is not zero.

Example

In the below code we will call a function empty() to check whether a list is empty or not and if the list is empty then we will insert elements to a list using push_back() function to check the result.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   list<int> myList; //to create a list
   //call empty() function to check if list is empty or not
   if (myList.empty())
      cout << "my list is empty\n";
   else
      cout << "my list isn’t empty\n";
   //push_back() is used to insert element in a list
   myList.push_back(1);
   myList.push_back(2);
   myList.push_back(3);
   myList.push_back(4);
   if (myList.empty())
      cout << "my list is empty\n";
   else
      cout << "my list is not empty\n";
   return 0;
}

Output

If we run the above code it will generate the following output

my list is empty
my list is not empty

In the below code we are trying to multiply the numbers from 1-10 and for that −

  • First insert elements into the list using push_back() function

  • Traverse the list until it won’t get empty using the function empty().

  • Print the result

Example

#include <bits/stdc++.h> 
using namespace std;
int main (){
   list<int> myList;
   int product = 0;
   for (int i=1;i<=10;++i)
   mylist.push_back(i);
   while (!mylist.empty()){
      product *= myList.front();
      myList.pop_front();
   }
   cout << "product of numbers from 1-10 is: " <<product << '\n';
   return 0;
}

Output

If we run the above code it will generate the following output

product of numbers from 1-10 is: 3628800
raja
Published on 02-Mar-2020 07:11:32
Advertisements