C++ Standard Library C++ STL Library

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

template<class Key, class Compare, class Alloc>
void swap(
    multiset<Key,Compare,Alloc>& lhs,
    multiset<Key,Compare,Alloc>& rhs 
);
template<class Key, class Compare, class Alloc>
void swap(
    multiset<Key,Compare,Alloc>& lhs,
    multiset<Key,Compare,Alloc>& rhs 
 );

Parameters

lhs First multiset.
rhs Second multiset.

Return Value

None.

Time Complexity

Constant i.e, Θ(1)

Example:

In the example below, the 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;

  swap(MyMSet1, 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