list emplace() function in C++ STL

C++Server Side ProgrammingProgramming

Given is the task to show the working of list emplace() function in C++.

The list::emplace() function is a part of the C++ standard template library. It is used to insert values inside a list at a specified position by the user.

<list> header file should be included to call this function.

Syntax

List_Name.emplace(position,element)

Parameters

This function takes two parameters −

First is position, which represents the position at which the new element has to be placed and the second is value, which represents the element that has to be inserted inside the list at the position.

Return Value

The function returns an iterator that point at the newly inserted element.

Example

Input: list<int> L = { 1,2,3 }
Output: 6 1 2 3

Explanation − Here we created a list “L” of type int having values 1, 2 and 3. Then we created the object “itr” which will work as our iterator as the emplace function returns an iterator. We chose the starting position of the list for placing the new element which is represented by the first argument. Our second argument is 6 which will be the new element to be added which generates the output as 6 1 2 3.

Approach used in the below program as follows −

  • First create a list of type int, let us say “Lt” and assign it some values.
  • Then create an object “itr” of type auto and initialize it by calling the emplace function. “itr” will be the iterator which will receive the return value of the emplace() function.
  • Then give arguments to the function, let’s say first argument will be Lt.end() to choose the ending position of the list and for the second argument, any value let’s say 7.

Algorithm

Start
Step 1->In function main()
   Initialize list<int> Lt={}
   Initialize auto itr=Lt.emplace(Lt.end(),7)
   Loop For itr=Lt.begin() and itr!=Lt.end() and itr++
   Print *itr
Stop

Example

 Live Demo

#include <iostream>
#include<list>
using namespace std;
int main() {
   list<int> Lt = { 3,4,5 };
   auto itr = Lt.emplace(Lt.begin(),7);
   Lt.emplace(itr,6);
   cout << "The List is: ";
   for (itr = Lt.begin(); itr != Lt.end(); itr++)
   cout << *itr << " ";
   return 0;
}

Output

If we run the above code it will generate the following output −

The List is: 6 7 3 4 5
raja
Published on 20-Jan-2020 07:26:29
Advertisements