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:
- position – it specifies the iterator which points to the position in the list where the new element is to be inserted.
- args – it specifies the elements to be inserted in the list container.
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
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)
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.


