multimap::swap() 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 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.


multimap_name.swap(multimap& multimap_name2);


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.


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: d: 2 e:4 f:6
Eve: a:1 b:3 c:5


 Live Demo

using namespace std;
int main(){
   multimap<int,char > mul_1;
   //declaring iterator to traverse the elements
   multimap<int,char>:: iterator i;
   //inserting elements to multimap1
   //inserting elements to multimap2
   //calling swap to swap the elements
   //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";


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

Updated on: 22-Apr-2020


Kickstart Your Career

Get certified by completing the course

Get Started