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:
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
forward_list< int > list1 = { 10, 20, 30, 40 };
forward_list< int > list2 = { 4, 9 };
list2.splice_after(list2.begin(), list1,
list1.begin(), list1.end());
cout << "Elements are: " << endl;
for ( auto it = list2.begin(); it != list2.end(); ++it)
cout << *it << " " ;
return 0;
}
|
OutputElements are:
4 20 30 40 9
Time Complexity: O(n)
Auxiliary Space: O(n)
Program 2:
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
forward_list< int > list1 = { 10, 20, 30, 40 };
forward_list< int > list2 = { 4, 9 };
list2.splice_after(list2.begin(), list1,
list1.before_begin(), list1.end());
cout << "Elements are: " << endl;
for ( auto it = list2.begin(); it != list2.end(); ++it)
cout << *it << " " ;
return 0;
}
|
OutputElements are:
4 10 20 30 40 9
Time Complexity: O(n)
Auxiliary Space: O(n)