C++ Standard Library C++ STL Library

C++ unordered_multiset - swap() Function



The C++ unordered_multiset swap() function is used to exchange all elements of one unordered_multiset with all elements of another unordered_multiset. To apply this function, the data-type of both unordered_multisets must be same, although the size may differ.

Syntax

template<class Key, class Hash, class Pred, class Alloc>
void swap(
    unordered_multiset<Key,Hash,Pred,Alloc>& lhs,
    unordered_multiset<Key,Hash,Pred,Alloc>& rhs 
);

Parameters

lhs First unordered_multiset.
rhs Second unordered_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 unordered_multiset uMSet1 with all elements of unordered_multiset uMSet2.

#include <iostream>
#include <unordered_set>
using namespace std;
 
int main (){
  unordered_multiset<int> uMSet1{10, 20, 30, 40, 50};
  unordered_multiset<int> uMSet2{5, 55, 555};

  unordered_multiset<int>::iterator it;

  cout<<"Before Swapping, The uMSet1 contains:";
  for(it = uMSet1.begin(); it != uMSet1.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nBefore Swapping, The uMSet2 contains:";
  for(it = uMSet2.begin(); it != uMSet2.end(); ++it)
    cout<<" "<<*it;

  swap(uMSet1, uMSet2);

  cout<<"\n\nAfter Swapping, The uMSet1 contains:";
  for(it = uMSet1.begin(); it != uMSet1.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nAfter Swapping, The uMSet2 contains:";
  for(it = uMSet2.begin(); it != uMSet2.end(); ++it)
    cout<<" "<<*it;

  return 0;
}

The output of the above code will be:

Before Swapping, The uMSet1 contains: 50 40 30 20 10
Before Swapping, The uMSet2 contains: 555 55 5

After Swapping, The uMSet1 contains: 555 55 5
After Swapping, The uMSet2 contains: 50 40 30 20 10

❮ C++ <unordered_set> Library