C++ multimap - swap() Function
The C++ multimap::swap function is used to exchange all elements of one multimap with all elements of another multimap. To apply this function, the data-type of both multimaps must be same, although the size may differ.
Syntax
void swap (multimap& other);
void swap (multimap& other);
Parameters
other |
Specify multimap, whose elements need to be exchanged with another multimap. |
Return Value
None.
Time Complexity
Constant i.e, Θ(1)
Example:
In the example below, the multimap::swap function is used to exchange all elements of multimap MyMMap1 with all elements of multimap MyMMap2.
#include <iostream> #include <map> using namespace std; int main (){ multimap<string, string> MyMMap1; multimap<string, string> MyMMap2; multimap<string, string>::iterator it; //elements of MyMMap1 MyMMap1.insert(pair<string, string>("USA", "New York")); MyMMap1.insert(pair<string, string>("USA", "Washington")); MyMMap1.insert(pair<string, string>("CAN", "Toronto")); //elements of MyMMap2 MyMMap2.insert(pair<string, string>("CAN", "Montreal")); MyMMap2.insert(pair<string, string>("IND", "Delhi")); cout<<"Before Swapping, The MyMMap1 contains:\n"; for(it = MyMMap1.begin(); it != MyMMap1.end(); ++it) cout<<it->first<<" "<<it->second<<"\n"; cout<<"\nBefore Swapping, The MyMMap2 contains:\n"; for(it = MyMMap2.begin(); it != MyMMap2.end(); ++it) cout<<it->first<<" "<<it->second<<"\n"; MyMMap1.swap(MyMMap2); cout<<"\n\nAfter Swapping, The MyMMap1 contains:\n"; for(it = MyMMap1.begin(); it != MyMMap1.end(); ++it) cout<<it->first<<" "<<it->second<<"\n"; cout<<"\nAfter Swapping, The MyMMap2 contains:\n"; for(it = MyMMap2.begin(); it != MyMMap2.end(); ++it) cout<<it->first<<" "<<it->second<<"\n"; return 0; }
The output of the above code will be:
Before Swapping, The MyMMap1 contains: CAN Toronto USA New York USA Washington Before Swapping, The MyMMap2 contains: CAN Montreal IND Delhi After Swapping, The MyMMap1 contains: CAN Montreal IND Delhi After Swapping, The MyMMap2 contains: CAN Toronto USA New York USA Washington
❮ C++ <map> Library