C++ unordered_map swap() Function
Example
Swap the contents of two unordered maps:
unordered_map<string, int> people = {{"John", 32}, {"Adele", 45}, {"Bo", 29}};
unordered_map<string, int> friends = {{"Jenny", 22}, {"Liam", 24}};
people.swap(friends);
cout << "people has " << people.size() << " elements\n";
cout << "friends has " << friends.size() << " elements";
Definition and Usage
The swap() function swaps the contents of two unordered maps. After the swap, each unordered map has the elements that the other one had before.
Both unordered maps must have the same key type and value type.
The swap function is defined in the <unordered_map> header file.
Syntax
unordered_map.swap(otherMap)
Parameter Values
| Parameter | Description |
|---|---|
| otherMap | Required. Another unordered map with the same key type and value type. |
Technical Details
| Returns: | Nothing (void). |
|---|
Related Pages
Read more about unordered maps in our Unordered Map Tutorial.