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