Skip to content
Related Articles

Related Articles

list emplace() function in C++ STL
  • Difficulty Level : Basic
  • Last Updated : 19 Jul, 2018

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)

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :