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