list front() function in C++ STL

C++Server Side ProgrammingProgramming

C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

In this article we will be discussing the working, syntax and examples of list::front() 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::front() ?

list::front() is an inbuilt function in C++ STL which is declared in <list> header file. front() returns the direct reference to the element which is on the first position in the list container.

When we use this function with an empty list, then it cause an undefined behavior.

Syntax

list_container.front();

This function accepts no parameter.

Return Value

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

Example

/* In the below code we are trying to catch the first element in a list using the function front() and display the result */

Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
//Create a list
list<int> myList;
//insert elements to the List
myList.push_back(3);
myList.push_back(2);
myList.push_back(21);
myList.push_back(11);
//catch the first element of a List
int first_ele = myList.front();
cout<<"first element in a list is : "<<first_ele;
return 0;
}

Output

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

first element in a list is : 3

Example

/* In the below code we are replacing the value of the first element with the last element and for that we need to have access of first and last value which will be done through calling front() and back() function. */

Live Demo

#include <iostream>
#include <list>
int main (){
std::list<int> myList;
myList.push_back(77);
myList.push_back(2);
myList.push_back(21);
myList.push_back(23);
myList.front() = myList.back();
std::cout << "replacing first element with the last element : " << myList.front() << '';
return 0;
}

Output

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

replacing first element with the last element : 23
Updated on 02-Mar-2020 08:06:38