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