# multimap::swap() in C++ STL

C++Server Side ProgrammingProgramming

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 storing 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 swap 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({‘a’, 1});
odd.insert({‘b’, 3});
odd.insert({‘c’, 5});
eve.insert({‘d’, 2});
eve.insert({‘e’, 4});
eve.insert({‘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,char > mul_1;
multimap<int,char>mul_2;
//declaring iterator to traverse the elements
multimap<int,char>:: iterator i;
//inserting elements to multimap1
mul_1.insert(make_pair(0,'a'));
mul_1.insert(make_pair(1,'b'));
mul_1.insert(make_pair(2,'c'));
mul_1.insert(make_pair(3,'d'));
//inserting elements to multimap2
mul_2.insert(make_pair(4,'e'));
mul_2.insert(make_pair(5,'f'));
mul_2.insert(make_pair(6,'g'));
//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:
4 e
5 f
6 g
Elements in multimap2 are: 0 a
1 b
2 c
3 d
Published on 22-Apr-2020 11:18:26