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