List push_front() function in C++ STL


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

push_front() is an inbuilt function in C++ STL which is declared in header file. push_front() is used to push (insert) the element at the beginning of the list container. If the container is empty, it pushes the element at the first position and the element becomes the first element and if the container is having the elements beforehand the function pushes the element passed to it to the front and the existing element which is on first position will become the second element. This function increases the size of the container by 1.

Syntax

void push_front (const value_type& element1);
void push_front (value_type&& element1);
This function accepts only 1 element which is to be pushed/inserted.

Return Value

This function returns nothing.

Example

#include <bits/stdc++.h>
using namespace std;
int main(){
   //create a list
   list myList;
   //insert elements
   myList.push_back(1);
   myList.push_back(2);
   myList.push_back(3);
   myList.push_back(4);
   //List before applying push_front()
   cout<<"List : ";
   for (auto i = myList.begin(); i!= myList.end(); i++)
      cout << *i << " ";
   //calling push_front()
   myList.push_front(0);
   cout<<"\nList after calling push_front() : ";
   for (auto i = myList.begin(); i!= myList.end(); i++)
      cout << *i << " ";
   return 0;
}

Output

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

List : 1 2 3 4
List after calling push_front(): 4 3 2 1

Example

 Live Demo

#include <iostream>
#include <list>
int main (){
   //adding two integer values with the value 30
   std::list<int> myList (2,30);
   myList.push_front (20);
   myList.push_front (10);
   std::cout<<"elements in my list are : ";
   for (std::list<int>::iterator i = myList.begin(); i!= myList.end(); ++i)
      std::cout << ' ' << *i;
   std::cout << '\n';
   return 0;
}

Output

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

Elements in my list are : 10 20 30 30

Updated on: 26-Feb-2020

335 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements