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:

Return value: The function has no return value.

Below program demonstrates the above function:



Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}
chevron_right

Output:
Elements are: 
4 20 30 40 9

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}
chevron_right

Output:
Elements are: 
4 10 20 30 40 9

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.




Article Tags :
C++
Practice Tags :