C++ Standard Library C++ STL Library

C++ map - swap() Function



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

Syntax

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

Parameters

lhs First map.
rhs Second 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 map MyMap1 with all elements of map MyMap2.

#include <iostream>
#include <map>
using namespace std;
 
int main (){
  map<string, int> MyMap1;
  map<string, int> MyMap2;
  map<string, int>::iterator it;

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

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

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

  swap(MyMap1, MyMap2);

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

  return 0;
}

The output of the above code will be:

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

Before Swapping, The MyMap2 contains:
Adam  3100
Nora  3000


After Swapping, The MyMap1 contains:
Adam  3100
Nora  3000

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

❮ C++ <map> Library