C++ <list> - swap() Function
The C++ <list> swap() function is used to exchange all elements of one list with all elements of another list. To apply this function, the data-type of both lists must be same, although the size may differ.
Syntax
template<class T, class Alloc> void swap( list<T,Alloc>& lhs, list<T,Alloc>& rhs );
template<class T, class Alloc> void swap( list<T,Alloc>& lhs, list<T,Alloc>& rhs );
Parameters
lhs |
First list. |
rhs |
Second list. |
Return Value
None.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the swap() function is used to exchange all elements of list MyList1 with all elements of list MyList2.
#include <iostream> #include <list> using namespace std; int main (){ list<int> MyList1{10, 20, 30, 40, 50}; list<int> MyList2{5, 55, 555}; list<int>::iterator it; cout<<"Before Swapping, The MyList1 contains:"; for(it = MyList1.begin(); it != MyList1.end(); ++it) cout<<" "<<*it; cout<<"\nBefore Swapping, The MyList2 contains:"; for(it = MyList2.begin(); it != MyList2.end(); ++it) cout<<" "<<*it; swap(MyList1, MyList2); cout<<"\n\nAfter Swapping, The MyList1 contains:"; for(it = MyList1.begin(); it != MyList1.end(); ++it) cout<<" "<<*it; cout<<"\nAfter Swapping, The MyList2 contains:"; for(it = MyList2.begin(); it != MyList2.end(); ++it) cout<<" "<<*it; return 0; }
The output of the above code will be:
Before Swapping, The MyList1 contains: 10 20 30 40 50 Before Swapping, The MyList2 contains: 5 55 555 After Swapping, The MyList1 contains: 5 55 555 After Swapping, The MyList2 contains: 10 20 30 40 50
❮ C++ <list> Library