C++ Standard Library C++ STL Library

C++ <list> - push_front() Function



The C++ list::push_front function is used to add a new element at the beginning of the list. Addition of new element always occurs before its current first element and every addition results into increasing the container size by one.

Syntax

void push_front (const value_type& val);
void push_front (const value_type& val);
void push_front (value_type&& val);

Parameters

val Specify the new element which need to be added in the list.

Return Value

None.

Time Complexity

Constant i.e, Θ(1)

Example:

In the example below, the list::push_front function is used to add new elements in the list called MyList.

#include <iostream>
#include <list>
using namespace std;
 
int main (){
  list<int> MyList;
  list<int>::iterator it;

  //add new elements in the list
  MyList.push_front(10);
  MyList.push_front(20);
  MyList.push_front(30);
  MyList.push_front(40);
  MyList.push_front(50);


  cout<<"MyList contains:";
  for(it = MyList.begin(); it != MyList.end(); ++it)
    cout<<" "<<*it;

  return 0;
}

The output of the above code will be:

MyList contains: 50 40 30 20 10

❮ C++ <list> Library