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;
}
|
Output
Elements 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;
}
|
Output
Elements are:
4 10 20 30 40 9
Time Complexity: O(n)
Auxiliary Space: O(n)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
28 Jun, 2023
Like Article
Save Article