list::front() and list::back() in C++ STL


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

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 performs 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 the list::front()?

list::front() is an inbuilt function in C++ STL which is declared in header file. front() is used to refer to the first element of the list container. This function returns a direct reference to the first element only, whereas list::begin() returns an iterator which is pointing to the first element of the associated list container.

Syntax

mylist.front();

Parameters

This function accepts no parameter

Example

Input: list<int> List_container= {10, 11, 13, 15};
      List_container.front();
Output:
      Front element= 10;

Return Value

This function returns the reference to the first element of the associated list container.

Example

 Live Demo

#include <iostream>
#include <list>
using namespace std;
int main(){
   list<int> myList = { 10, 20, 30, 40, 50 };
   cout<<"Front element in my list is : "<<myList.front();
   return 0;
}

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

Front element in my list is : 10

What is the list::back()?

list::back() is an inbuilt function in C++ STL which is declared in header file. back() is used to refer to the last element of the list container. This function returns a direct reference to the last element only. When the list is empty then the function performs an undefined behaviour.

Syntax

mylist.back();

Parameters

This function accepts no parameter

Example

Input: list<int> List_container= {10, 11, 13, 15};
      List_container.back();
Output:
      Front element= 15;

Return Value

This function returns the reference to the last element of the list container.

Example

 Live Demo

#include <iostream>
#include <list>
using namespace std;
int main(){
   list<int> myList = { 10, 20, 30, 40, 50 };
   cout<<"Last element in list is : "<< myList.back();
   return 0;
}

Output

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

Last element in list is : 50

Updated on: 06-Mar-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements