C++ map - swap() Function
The C++ map::swap function is used to exchange all elements of one map with all elements of another map. To apply this function, the data-type of both maps must be same, although the size may differ.
Syntax
void swap (map& other);
void swap (map& other);
Parameters
other |
Specify map, whose elements need to be exchanged with another map. |
Return Value
None.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the map::swap function is used to exchange all elements of map MyMap1 with all elements of map MyMap2.
#include <iostream> #include <map> using namespace std; int main (){ map<string, int> MyMap1; map<string, int> MyMap2; map<string, int>::iterator it; //elements of MyMap1 MyMap1["John"] = 2500; MyMap1["Jack"] = 2600; MyMap1["Ella"] = 2000; //elements of MyMap2 MyMap2["Nora"] = 3000; MyMap2["Adam"] = 3100; cout<<"Before Swapping, The MyMap1 contains:\n"; for(it = MyMap1.begin(); it != MyMap1.end(); ++it) cout<<it->first<<" "<<it->second<<"\n"; cout<<"\nBefore Swapping, The MyMap2 contains:\n"; for(it = MyMap2.begin(); it != MyMap2.end(); ++it) cout<<it->first<<" "<<it->second<<"\n"; MyMap1.swap(MyMap2); cout<<"\n\nAfter Swapping, The MyMap1 contains:\n"; for(it = MyMap1.begin(); it != MyMap1.end(); ++it) cout<<it->first<<" "<<it->second<<"\n"; cout<<"\nAfter Swapping, The MyMap2 contains:\n"; for(it = MyMap2.begin(); it != MyMap2.end(); ++it) cout<<it->first<<" "<<it->second<<"\n"; return 0; }
The output of the above code will be:
Before Swapping, The MyMap1 contains: Ella 2000 Jack 2600 John 2500 Before Swapping, The MyMap2 contains: Adam 3100 Nora 3000 After Swapping, The MyMap1 contains: Adam 3100 Nora 3000 After Swapping, The MyMap2 contains: Ella 2000 Jack 2600 John 2500
❮ C++ <map> Library