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