In: Computer Science
In C++ please.
3. splice() is a specialized method that inserts one list into another in constant time but destroys the first list. Explain why this may be implemented for the list but not for any other sequential container. Give an example usage of splice()
3. splice() is a specialized method that inserts one list into another in constant time but destroys the first list. Explain why this may be implemented for the list but not for any other sequential container. Give an example usage of splice()
Ans:-
The list::splice() may be a built-in function in C++ STL which
is employed to transfer elements from one list to a different
.
We can use splice() function in 3 ways:
1.Transfer all the weather of list x into another list at some
position.
2.Transfer only the element pointed by i from list x into another
list at some position.
3.Transfers the range [first, last] from list x into another list
at some position.
The splice() function move the element of list from one list to another list. But also at the time it's remove from one list to another list. splice() is a specialized method that inserts one list into another in constant time but destroys the first list. Rather it's change or empty the first lilst.
It's implement only for list because it's use list's index values for use splice function or we can say that to pass the parameters to the splice() function.
Syntax:
list1Name.splice (iterator position, list2) or listName.splice (iterator position, list2, iterator i) or list1Name.splice (iterator position, list2, iterator first, iterator last)
Parameters:
usage of splice():-
The use of splice() function to remove element from one list at constant time and add it to anther list.
Example:-
// list::splice() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
// init lists
list<int> list1 = { a, b, c };
list<int> list2 = { d, e };
list<int> list3 = { f, g, h };
// transfer all the elements of list2
list1.splice(list1.begin(), list2);
// at the beginning of list1
cout << "list list1 after splice operation" << endl;
for (auto x : list1)
cout << x << " ";
// transfer all the elements of list1
list3.splice(list3.end(), list1);
// at the end of list3
cout << "\nlist list3 after splice operation" << endl;
for (auto x : list3)
cout << x << " ";
return 0;
}
Output:-
list list1 after splice operation d e a b c list list3 after splice operation f g h d e a b c