forward_list::front() and forward_list::empty() in C++ STL


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

What is a Forward_list in STL?

Forward list are sequence containers that allow constant time insert and erase operations anywhere within the sequence. Forward list are implement as a singly-linked lists. The ordering is kept by the association to each element of a link to the next element in the sequence.

What is forward_list::front()?

forward_list::front() is an inbuilt function in C++ STL which is declared in <forward_list> header file. front() returns the iterator which is referred to the first element in the forward_list container.

Syntax

forwardlist_container.front();

This function accepts no parameter.

Return Value

This function returns the iterator pointing to the first element of the container.

Example

/* In the below code we are creating a forward list and inserting elements to it then we will call front() function to fetch the first element in a forward list. */

 Live Demo

#include <forward_list>
#include <iostream>
using namespace std;
int main(){
   forward_list<int> forwardList = {2, 6, 1, 0 };
   cout<<"my first element in a forward list is: ";
   cout<<forwardList.front();
   return 0;
}

Output

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

my first element in a forward list is: 2

What is forward_list::empty()?

forward_list::empty() is an inbuilt function in C++ STL which is declared in <forward_list> header file. empty() returns true if the forward list container is empty, else it will return false. This function checks if the size of the container is 0

Syntax

bool forwardlist_container.empty();

This function accepts no parameter.

Return Value

This function returns true if the container’s size is 0 else it will return false

Example

/* In the below code we are creating a forward list then we will check whether the list is shown empty or not by calling the empty() function. After that, we will insert elements to a forward list and then we will again call empty() function to check what will be the result now. */

 Live Demo

#include <forward_list>
#include <iostream>
using namespace std;
int main(){
   forward_list<int> forwardList = {};
   if (forwardList.empty()){
      cout << "Yess forward list is empty\n";
   }
   forwardList = {1, 3, 4, 5};
   if (forwardList.empty()){
      cout << "Yess forward list is empty\n";
   } else {
      cout << "No forward list is not empty\n";
   }
   return 0;
}

Output

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

Yess forward list is empty
No forward list is not empty

Updated on: 02-Mar-2020

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements