Given is the task to show the working of forward_list::emplace_after() and forward_list::emplace_front() functions in c++.
A forward_list only keeps linkage with the next element unlike normal list that keeps linkage with the next as well as the preceding elements, which helps iterations in both directions. But forward_list can only iterate in the forward direction.
The forward_list::emplace_after() and forward_list::emplace_front() functions are a part of the c++ standard library.
The forward_list::emplace_after() function is used to insert a new element inside a list after the element whose position is specified inside the argument
The forward_list::emplace_front() function is used to insert an element in the beginning of the list.
<forward_list> header file should be included to call the function.
Forward_List_Name.emplace_after(iterator , element);
The function accepts two parameters −
Iterator, the iterator contains the position at which the new element has to be placed.
Element, it contains the element that has to be placed.
The function returns an iterator that points to the new element that has been placed inside the forward list.
Forward_List_Name.emplace_front(element);
The function accepts one parameter.
The function does not return anything.
Input: 11,34,56 Output: 41 11 34 56
Explanation −
Here we created a forwards list Lt with elements 11,34,56. Then we called the emplace_front() function that is used to insert a new element at the beginning of a forward list and here that element is 41.
So when we print the forward list, the output generated is 41 11 34 56 which has the first element as 41.
Approach used in the below program as follows −
Start Step 1->In function main() Initialize forward_list<int> Lt={} Call function Lt.emplace_front() Initialize auto itr=Lt.end(); Call Lt.emplace_after(itr , element) End Stop
#include<iostream> #include<list> using namespace std; int main() { forward_list<int> Lt = { 5,6,7,8 }; //Using the emplace_front() function to place element at the beginning. Lt.emplace_front(3); auto itr = Lt.end(); /*Using the emplace_after() function to place an element after the location specified*/ Lt.emplace_after(itr , 10) //Displaying the list for(auto itr = Lt.begin() ; itr!=Lt.end ; itr++) cout<<” *itr ”<<” ”; return 0; }
If we run the above code it will generate the following output −
3 5 6 7 8 10