C++ Standard Library C++ STL Library

C++ <list> - emplace() Function



The C++ list::emplace function is used to insert new element at specified position in a list. Each insertion of element increases the list container size by one.

Syntax

template <class... Args>
iterator emplace (const_iterator position, Args&&... args);

Parameters

position Specify the position in the list where the new element need to be inserted.
args Arguments forwarded to construct the new element.

Return Value

An iterator that points to the newly emplaced element.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the list::emplace function is used to insert new element at specified position in a list MyList.

#include <iostream>
#include <list>
using namespace std;
 
int main (){
  list<int> MyList{10, 20, 30, 40, 50};
  list<int>::iterator it;
  
  it = MyList.begin();
  advance(it, 2);
  //insert a new element at position = 3
  MyList.emplace(it, 100);

  it = MyList.end();
  //insert a new element at the end of the list
  MyList.emplace(it, 200);

  //insert a another new element at the end of the list
  MyList.emplace(it, 300);

  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: 10 20 100 30 40 50 200 300 

Example:

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

#include <iostream>
#include <list>
using namespace std;
 
int main (){
  list<string> MyList{"JAN", "MAR", "APR", "MAY"};
  list<string>::iterator it;

  it = MyList.begin();
  it++;
  //insert a new element at position = 2
  MyList.emplace(it, "FEB");

  it = MyList.end();
  //insert a new element at the end of the list
  MyList.emplace(MyList.end(), "JUN");

  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: JAN FEB MAR APR MAY JUN 

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;
  
  it = MyList.begin();
  //insert a new elements in the list
  MyList.emplace(it, 1, "JAN");
  MyList.emplace(it, 2, "FEB");
  MyList.emplace(it, 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: (1,JAN) (2,FEB) (3,MAR) 

❮ C++ <list> Library

5