C++ Standard Library C++ STL Library

C++ unordered_map - swap() Function



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

Syntax

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

Parameters

lhs First unordered_map.
rhs Second unordered_map.

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_map uMap1 with all elements of unordered_map uMap2.

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

  //elements of uMap1
  uMap1["John"] = 2500;
  uMap1["Jack"] = 2600;
  uMap1["Ella"] = 2000;

  //elements of uMap2
  uMap2["Nora"] = 3000;
  uMap2["Adam"] = 3100;

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

  swap(uMap1, uMap2);

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

  return 0;
}

The output of the above code will be:

Before Swapping, The uMap1 contains:
Ella  2000
John  2500
Jack  2600

Before Swapping, The uMap2 contains:
Adam  3100
Nora  3000


After Swapping, The uMap1 contains:
Adam  3100
Nora  3000

After Swapping, The uMap2 contains:
Ella  2000
John  2500
Jack  2600

❮ C++ <unordered_map> Library