Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ forward_list::push_front function is used to add a new element at the beginning of the forward_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 (value_type&& val);

Parameters

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

Return Value

None.

Time Complexity

Constant i.e, Θ(1).

Example:

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

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

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


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

  return 0;
}

The output of the above code will be:

The forward_list contains: 50 40 30 20 10

❮ C++ <forward_list> Library