Skip to content
Related Articles

Related Articles

Improve Article
multimap::swap() in C++ STL
  • Last Updated : 25 Jan, 2018

multimap::swap() is used to swap the contents of one multimap with another multimap of same type and size.

Syntax:-

multimap1.swap(multimap2)

Parameters :
The name of the multimap with which
the contents have to be swapped.
Result :
All the elements of the 2 multimap are swapped.

Examples:

Input:   multimap1 = { ('a',1), ('b',2), ('c',3)
         multimap2 = ( ('d',4), ('e',5) )
         multimap1.swap(multimap2);

Output:  MultiMap 1 data
         ('d', 4), ('e', 5) 

         MultiMap 2 data
         ('a',1), ('b',2), ('c',3)
        

Input:  multimap1 = { ('abc',10) , ('bef',12) , ('efg',13)
        multimap2 = ( ('def',14), ('ehi',15) )
        multimap1.swap(multimap2);

Output: multimap 1 data
        ('def',14), ('ehi',15)

        multimap 2 data
        ('abc',10) , ('bef',12) , ('efg',13)




// CPP Program to illustrate...
#include<iostream>
#include<map>
using namespace std;
  
int main()
{
    // initialize multimap
    multimap<char,int > m1;
    multimap<char,int> m2;
      
    // iterator for iterate all 
    // element of multimap
    multimap<char,int >:: iterator iter;
      
    // multimap1 data
    m1.insert(make_pair('a',1));
    m1.insert(make_pair('b',2));
    m1.insert(make_pair('c',3));
      
    // multimap2 data
    m2.insert(make_pair('d',4));
    m2.insert(make_pair('e',5));
      
    // swap multimap1 data with
    // multimap2 data
    m1.swap(m2);
      
      
    // multimap1 data
    cout << "MultiMap 1 data" << "\n";
    for( iter = m1.begin() ;
         iter != m1.end() ; iter++)
      
    cout << (*iter).first << " " 
         << (*iter).second << "\n";
      
      
    // multimap2 data
    cout << "MultiMap 2 data" << "\n";
    for( iter = m2.begin() ;
         iter != m2.end() ; iter++ )
       
    cout << (*iter).first << " " 
         << (*iter).second << "\n";
}

Output:-

MultiMap 1 data
d 4
e 5
MultiMap 2 data
a 1
b 2
c 3
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :