.swap()
Anonymous contributor
Published Oct 28, 2024
Contribute to Docs
In C++, .swap()
function exchanges the contents of two maps in constant time, provided the maps are of the same type, though their sizes may differ.
Syntax
map1.swap(map2);
map1
: The first map whose contents will be swapped.map2
: The second map to exchange contents withmap1
.
Note: If
map1
andmap2
are not of the same type (i.e., they do not have the same key and value types), a compilation error will occur becausestd::map::swap()
requires both maps to have the same type.
Example
The following example shows how the swap()
funcrion works:
#include <iostream>#include <map>using namespace std;int main() {map<int, string> map1{{1, "one"}, {2, "two"}, {3, "three"}};map<int, string> map2{{4, "four"}, {5, "five"}, {6, "six"}};cout << "Before swap Map1:\n";for(map<int, string>::iterator it = map1.begin();it != map1.end();++it) {cout << "Key: " << it->first<< ", Value: " << it->second << endl;}cout << "Before swap Map2:\n";for(map<int, string>::iterator it = map2.begin();it != map2.end();++it) {cout << "Key: " << it->first<< ", Value: " << it->second << endl;}// Swapping the contents of map1 and map2map1.swap(map2);cout << "After swap Map1:\n";for(map<int, string>::iterator it = map1.begin();it != map1.end();++it) {cout << "Key: " << it->first<< ", Value: " << it->second << endl;}cout << "After swap Map2:\n";for(map<int, string>::iterator it = map2.begin();it != map2.end();++it) {cout << "Key: " << it->first<< ", Value: " << it->second << endl;}return 0;}
The output of the above code will be:
Before swap Map1:Key: 1, Value: oneKey: 2, Value: twoKey: 3, Value: threeBefore swap Map2:Key: 4, Value: fourKey: 5, Value: fiveKey: 6, Value: sixAfter swap Map1:Key: 4, Value: fourKey: 5, Value: fiveKey: 6, Value: sixAfter swap Map2:Key: 1, Value: oneKey: 2, Value: twoKey: 3, Value: three
Codebyte Example
Run the below codebyte example to know how the .swap()
function works:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours