C++ Standard Library C++ STL Library

C++ unordered_multimap - swap() Function



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

Syntax

void swap (unordered_multimap& other);

Parameters

other Specify unordered_multimap, whose elements need to be exchanged with another unordered_multimap.

Return Value

None.

Time Complexity

Constant i.e, Θ(1)

Example:

In the example below, the unordered_multimap::swap function is used to exchange all elements of unordered_multimap uMMap1 with all elements of unordered_multimap uMMap2.

#include <iostream>
#include <unordered_map>
using namespace std;
 
int main (){
  unordered_multimap<string, string> uMMap1;
  unordered_multimap<string, string> uMMap2;
  unordered_multimap<string, string>::iterator it;

  //elements of uMMap1
  uMMap1.insert(pair<string, string>("USA", "New York"));
  uMMap1.insert(pair<string, string>("USA", "Washington"));  
  uMMap1.insert(pair<string, string>("CAN", "Toronto"));

  //elements of uMMap2
  uMMap2.insert(pair<string, string>("CAN", "Montreal"));
  uMMap2.insert(pair<string, string>("IND", "Delhi"));

  cout<<"Before Swapping, The uMMap1 contains:\n";
  for(it = uMMap1.begin(); it != uMMap1.end(); ++it)
    cout<<it->first<<"  "<<it->second<<"\n";
  cout<<"\nBefore Swapping, The uMMap2 contains:\n";
  for(it = uMMap2.begin(); it != uMMap2.end(); ++it)
    cout<<it->first<<"  "<<it->second<<"\n";

  uMMap1.swap(uMMap2);

  cout<<"\n\nAfter Swapping, The uMMap1 contains:\n";
  for(it = uMMap1.begin(); it != uMMap1.end(); ++it)
    cout<<it->first<<"  "<<it->second<<"\n";
  cout<<"\nAfter Swapping, The uMMap2 contains:\n";
  for(it = uMMap2.begin(); it != uMMap2.end(); ++it)
    cout<<it->first<<"  "<<it->second<<"\n";

  return 0;
}

The output of the above code will be:

Before Swapping, The uMMap1 contains:
CAN  Toronto
USA  Washington
USA  New York

Before Swapping, The uMMap2 contains:
IND  Delhi
CAN  Montreal


After Swapping, The uMMap1 contains:
IND  Delhi
CAN  Montreal

After Swapping, The uMMap2 contains:
CAN  Toronto
USA  Washington
USA  New York

❮ C++ <unordered_map> Library