C++ Standard Library C++ STL Library

C++ <list> - emplace_back() Function



The C++ list::emplace_back function is used to insert new element at the end of the list, after the current last element. Each insertion of element increases the list container size by one.

Syntax

template <class... Args>
void emplace_back (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_back function is used to insert new element at the end 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 end of the list
  MyList.emplace_back(1000);

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

  //insert a another new element at the end of the list
  MyList.emplace_back(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: 10 20 30 40 50 1000 2000 3000  

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_back(1, "JAN");
  MyList.emplace_back(2, "FEB");
  MyList.emplace_back(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