multimap swap() function in C++ STL


In this article, we will be discussing the working, syntax, and examples of multimap swap() function in C++ STL.

What is Multimap in C++ STL?

Multimaps are the associative containers, which are similar to map containers. It also facilitates to store the elements formed by a combination of key-value and mapped value in a specific order. In a multimap container there can be multiple elements associated with the same key. The data is internally always sorted with the help of its associated keys.

What is multimap swap()?

multimap::swap() function is an inbuilt function in C++ STL, which is defined in <map> header file. swap() is used to swap the content of the two multimap containers. This function swaps the values of two multimap containers irrespective of the size of both the multimap containers.

When this function gets called it takes the parameter which is another multimap container and swaps the contents with the associated container.

Syntax

multimap_name.swap(multimap& multimap_name2);

Parameters

The function accepts the following parameter(s) −

  • map_name2 − This is another multimap container’s object whose data we want to swap with the associated multimap container.

Return value

This function returns nothing.

Input 

std::multimap<char, int> odd, eve;
odd.insert(make_pair(‘a’, 1));
odd.insert(make_pair(‘b’, 3));
odd.insert(make_pair(‘c’, 5));
eve.insert(make_pair(‘d’, 2));
eve.insert(make_pair(‘e’, 4));
eve.insert(make_pair(‘f’, 6));
odd.swap(eve);

Output 

Odd: d: 2 e:4 f:6
Eve: a:1 b:3 c:5

Example

 Live Demo

#include<iostream>
#include<map>
using namespace std;
int main(){
   multimap<int,int > mul_1;
   multimap<int,int> mul_2;
   //declaring iterator to traverse the elements
   multimap<int,int>:: iterator i;
   //inserting elements to multimap1
   mul_1.insert({1,10});
   mul_1.insert({2,20});
   mul_1.insert({3,30});
   mul_1.insert({4,40});
   mul_1.insert({5,50});
   //inserting elements to multimap2
   mul_2.insert({6,60});
   mul_2.insert({7,70});
   mul_2.insert({8,80});
   mul_2.insert({9,90});
   //calling swap to swap the elements
   mul_1.swap(mul_2);
   //elements of multimap1
   cout<<"Elements in multimap1 are: "<<"\n";
   for( i = mul_1.begin(); i!= mul_1.end(); i++){
      cout<<(*i).first<<" "<< (*i).second << "\n";
   }
   //elements of multimap2
      cout<<"\nElements in multimap2 are: ";
   for( i = mul_2.begin(); i!= mul_2.end(); i++){
      cout<<(*i).first<<" "<<(*i).second << "\n";
   }
}

Output

If we run the above code it will generate the following output −

Elements in multimap1 are:
6 60
7 70
8 80
9 90
Elements in multimap2 are: 1 10
2 20
3 30
4 40
5 50

Updated on: 22-Apr-2020

116 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements