multimap::swap() in C++ STL

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)

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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";
}
chevron_right

Output:-

MultiMap 1 data
d 4
e 5
MultiMap 2 data
a 1
b 2
c 3

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.





Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
C++
Practice Tags :