Open In App

forward_list insert_after() function in C++ STL

The forward_list::insert_after() is a builtin function in C++ STL which gives us a choice to insert elements at the position just after the element pointed by a given iterator in the forward list. The arguments in this function are copied at the desired position. Syntax: 

forward_list_name.insert_after(iterator position, element)

or,

forward_list_name.insert_after(iterator position, n, element)

or,

forward_list_name.insert_after(iterator position, itr1, itr2)

or,

forward_list_name.insert_after(iterator position, list)

Parameters: The function accepts different parameters based on the above different syntaxes. Let’s see every parameter in details and working of the above syntax.



Return Value :This function returns an iterator that points to the last inserted element. Below program illustrates the above mentioned function: 




// C++ program to illustrate the
// forward_list::insert_after() function
#include <forward_list>
#include <iostream>
#include <list>
 
using namespace std;
 
int main()
{
 
    forward_list<int> fwlist = { 1, 2, 3, 4, 5 };
    list<int> sampleList = { 8, 9, 10 };
 
    // This iterator points to the first element
    auto it_new = fwlist.begin();
 
    // New element to be inserted
    int element = 20;
 
    /******************************/
    /** IMPLEMENTING SYNTAX 1 *****/
    /******************************/
    it_new = fwlist.insert_after(it_new, element);
 
    cout << "After Syntax 1: ";
    for (auto it = fwlist.cbegin(); it != fwlist.cend(); it++) {
        cout << *it << " ";
    }
 
    // it_new points to new element inserted which is 20
    // Make it to point to next element
    it_new++;
 
    /******************************/
    /** IMPLEMENTING SYNTAX 2 *****/
    /******************************/
    it_new = fwlist.insert_after(it_new, 3, element);
 
    cout << "\n\nAfter Syntax 2: ";
    for (auto it = fwlist.cbegin(); it != fwlist.cend(); it++) {
        cout << *it << " ";
    }
 
    /******************************/
    /** IMPLEMENTING SYNTAX 3 *****/
    /******************************/
    it_new = fwlist.insert_after(it_new, sampleList.begin(),
                                sampleList.end());
 
    cout << "\n\nAfter Syntax 3: ";
    for (auto it = fwlist.cbegin(); it != fwlist.cend(); it++) {
        cout << *it << " ";
    }
 
    /******************************/
    /** IMPLEMENTING SYNTAX 4 *****/
    /******************************/
    it_new = fwlist.insert_after(it_new, { 50, 60 });
 
    cout << "\n\nAfter Syntax 4: ";
    for (auto it = fwlist.cbegin(); it != fwlist.cend(); it++) {
        cout << *it << " ";
    }
 
    return 0;
}

Output:

After Syntax 1: 1 20 2 3 4 5 

After Syntax 2: 1 20 2 20 20 20 3 4 5 

After Syntax 3: 1 20 2 20 20 20 8 9 10 3 4 5 

After Syntax 4: 1 20 2 20 20 20 8 9 10 50 60 3 4 5

Time Complexity: O(n)

Auxiliary Space: O(1)


Article Tags :