Open In App

list emplace() function in C++ STL

The list::emplace() is a built-in function in C++ STL which extends list by inserting new element at a given position.

Syntax:

list_name.emplace(position, element)

Parameters: The function accepts two mandatory parameters which are described below:

Return value: It returns a random access iterator which points to the newly inserted element.

Below programs illustrate the above function:

Program 1: 




// C++ program to illustrate the
// list::emplace() function
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 // declaration of list
 list<int> lis = { 5, 6, 7, 8, 9, 10 };
 
 auto it = lis.emplace(lis.begin(), 2);
 
 // inserts at the beginning of the list
 lis.emplace(it, 1);
 
 cout << "List: ";
 for (auto it = lis.begin(); it != lis.end(); ++it)
  cout << *it << " ";
 
 return 0;
}

Output
List: 1 2 5 6 7 8 9 10

Time Complexity: O(n)
Auxiliary Space: O(1)

Program 2: 




// C++ program to illustrate the
// list::emplace() function
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 // declaration of list
 list<pair<int, char> > lis;
 
 // inserts at the beginning of the list
 auto it = lis.emplace(lis.begin(), 4, 'a');
 
 // inserts at the beginning of the list
 lis.emplace(it, 3, 'b');
 
 cout << "List: ";
 
 for (auto it : lis)
  cout << "(" << it.first << ", " << it.second << ") ";
 
 return 0;
}

Output
List: (3, b) (4, a)

Time Complexity: O(n)
Auxiliary Space: O(1)


Article Tags :
C++