C++ Standard Library C++ STL Library

C++ <list> - emplace_front() Function



The C++ list::emplace_front function is used to insert new element at the beginning of the list, before the current first element. Each insertion of element increases the list container size by one.

Syntax

template <class... Args>
void emplace_front (Args&&... args);

Parameters

args Arguments forwarded to construct the new element.

Return Value

None.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the list::emplace_front function is used to insert new element at the beginning of the list MyList.

#include <iostream>
#include <list>
using namespace std;
 
int main (){
  list<int> MyList{10, 20, 30, 40, 50};
  list<int>::iterator it;

  //insert a new element at the beginning of the list
  MyList.emplace_front(1000);

  //insert a another new element at the beginning of the list
  MyList.emplace_front(2000);

  //insert a another new element at the beginning of the list
  MyList.emplace_front(3000);

  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: 3000 2000 1000 10 20 30 40 50  

Example:

Lets see another example where the list MyList contains paired values.

#include <iostream>
#include <list>
using namespace std;
 
int main (){
  list<pair<int,string>> MyList;
  list<pair<int,string>>::iterator it;
  
  //insert a new elements in the list
  MyList.emplace_front(1, "JAN");
  MyList.emplace_front(2, "FEB");
  MyList.emplace_front(3, "MAR");

  cout<<"MyList contains: ";
  for(it = MyList.begin(); it != MyList.end(); it++) {
   cout<<"("<<it->first<<","<<it->second<<") ";   
  }
  return 0;
}

The output of the above code will be:

MyList contains: (3,MAR) (2,FEB) (1,JAN) 

❮ C++ <list> Library