Tutorialspoint.dev

forward_list::splice_after() in C++ STL

forward_list::splice_after() is an inbuilt function in CPP STL which transfers the elements in the range of first+1 to last from a given forward_list to another forward_list. The elements are inserted after the element pointed to by position in the parameter.

Syntax:

forwardlist1_name.splice_after(position iterator, forwardlist2_name,
                                    first iterator, last iterator) 

Parameters: The function accepts four parameters which are specified as below:

  • position – Specifies the position in the forward_list after which the new elements are to be inserted.
  • forwardlist2_name– Specifies the list from which elements are to be inserted.
  • first– Specifies the iterator after which insertion is to be done.
  • last– Specifies the iterator till which insertion is to be done.

Return value: The function has no return value.

Below program demonstrates the above function:



Program 1:

// C++ program to illustrate
// splice_after() function
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // initialising the forward lists
    forward_list<int> list1 = { 10, 20, 30, 40 };
    forward_list<int> list2 = { 4, 9 };
  
    // splice_after operation performed
    // all elements except the first element in list1 is
    // inserted in list 2 between 4 and 9
    list2.splice_after(list2.begin(), list1,  
                  list1.begin(), list1.end());
  
    cout << "Elements are: " << endl;
  
    // loop to print the elements of second list
    for (auto it = list2.begin(); it != list2.end(); ++it)
        cout << *it << " ";
  
    return 0;
}

Output:

Elements are: 
4 20 30 40 9

Program 2:

// C++ program to illustrate
// splice_after() function
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // initialising the forward lists
    forward_list<int> list1 = { 10, 20, 30, 40 };
    forward_list<int> list2 = { 4, 9 };
  
    // splice_after operation performed
    // all elements of list1 are inserted
    // in list2 between 4 and 9
    list2.splice_after(list2.begin(), list1,
           list1.before_begin(), list1.end());
  
    cout << "Elements are: " << endl;
  
    // loop to print the elements of second list
    for (auto it = list2.begin(); it != list2.end(); ++it)
        cout << *it << " ";
  
    return 0;
}

Output:

Elements are: 
4 10 20 30 40 9


This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter