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