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
void swap (forward_list& other);
Parameters
other |
Specify forward_list, whose elements need to be exchanged with another forward_list. |
Return Value
None.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the forward_list::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; flist1.swap(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