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 example below, the swap() function is used to exchange all elements of forward_list flist1 with all elements of forward_list flist2.
#include <iostream> #include <forward_list> using namespace std; int main (){ forward_list<int> flist1{10, 20, 30, 40, 50}; forward_list<int> flist2{5, 55, 555}; forward_list<int>::iterator it; cout<<"Before Swapping, The flist1 contains:"; for(it = flist1.begin(); it != flist1.end(); ++it) cout<<" "<<*it; cout<<"\nBefore Swapping, The flist2 contains:"; for(it = flist2.begin(); it != flist2.end(); ++it) cout<<" "<<*it; swap(flist1, flist2); cout<<"\n\nAfter Swapping, The flist1 contains:"; for(it = flist1.begin(); it != flist1.end(); ++it) cout<<" "<<*it; cout<<"\nAfter Swapping, The flist2 contains:"; for(it = flist2.begin(); it != flist2.end(); ++it) cout<<" "<<*it; return 0; }
The output of the above code will be:
Before Swapping, The flist1 contains: 10 20 30 40 50 Before Swapping, The flist2 contains: 5 55 555 After Swapping, The flist1 contains: 5 55 555 After Swapping, The flist2 contains: 10 20 30 40 50
❮ C++ <forward_list> Library