In the C++ programming language, maps are containers that are present in the Standard Template Library. These are used to store the elements in the form of key-value pairs. The sorting of the values is dependent on the keys internally.
In C++ , the map::swap function is a member function of the STL map container. It is commonly used to swap (or exchange) the contents of two maps, but both maps must be of the same type, although sizes may differ. It is very useful when we need to replace one map with another or exchange data between two maps without copying elements individually.
Syntax
It has the following syntax:
void swap (map& x);
map1.swap( map2 ) or swap( map1, map2 )
In this syntax,
- x: The map container to exchange the contents with.
- Map1: It is the first object of the map.
- Map2: It is the second object of the map.
Let us take an example to swap the elements of one map to another map using the map swap function in C++.
Example
#include <iostream>
#include <map>
using namespace std; //using standard namespace
int main(void) { //main function
// map m1 initialized with key value pairs
map<char, int> m1 = {
{'a', 1},
{'b', 2},
{'c', 3},
{'d', 4},
{'e', 5},
};
// Declared map m2
map<char, int> m2;
cout << "Before swapping, the map m1 contains the following elements" << endl;
for ( auto it = m1.begin(); it != m1.end(); ++it ) {
cout << it->first << " = " << it->second << endl;
}
// called the swap( ) function to swap m1 map with m2 map
m2.swap(m1);
cout << "After swapping, map m1 contains no elements" << endl;
for (auto it = m1.begin(); it != m1.end(); ++it) {
cout << it->first << " = " << it->second << endl;
}
cout << "Now, map m2 contains the following elements after swapping with the m1 map " << endl;
for ( auto it = m2.begin(); it != m2.end(); ++it ) {
cout << it->first << " = " << it->second << endl;
}
return 0;
}
Output:
Before swapping, the map m1 contains the following elements
a = 1
b = 2
c = 3
d = 4
e = 5
After swapping, map m1 contains no elements
Now, map m2 contains the following elements after swapping with the m1 map
a = 1
b = 2
c = 3
d = 4
e = 5
Explanation:
In this example, we demonstrate the use of the map::swap function in C++. First, we have initialized m1 with key-value pairs and declared an empty map m2. After calling the m2.swap(m1) function, the contents of m1 and m2 are exchanged, which leaves m1 empty and m2 containing all the elements originally in m1.
C++ map::swap Example to Swap Two Maps with Different Data
Let us take an example to exchange the contents of two maps, map1 and map2, using the map::swap function in C++.
Example
#include <iostream>
#include <map>
using namespace std; //using standard namespace
int main ( ) //main function
{
map<char, int> map1;
map<char, int> map2;
// Putting data to map1
map1['x'] = 100;
map1['y'] = 200;
// Putting data to map2
map2['a'] = 110;
map2['b'] = 220;
map2['c'] = 330;
// calling the swap ( ) function to swap map map1 with map2
map1.swap( map2 );
cout <<"Before swapping, the map map1 contains the following data : \n";
for ( map<char, int>::iterator it = map1.begin( ); it != map1.end( ); ++it ) {
cout << it -> first << " => " << it -> second << '\n';
}
cout <<"Before swapping, the map map2 contains the following data : \n";
for ( map<char,int> :: iterator it = map2.begin( ); it != map2.end( ); ++it ) {
cout << it -> first << " => " << it -> second << '\n';
}
cout <<"After swapping, the map map1 contains the following data : \n";
for ( map<char, int>::iterator it = map1.begin( ); it != map1.end( ); ++it ) {
cout << it -> first << " => " << it -> second << '\n';
}
cout <<"After swapping, the map map2 contains the following data : \n";
for ( map<char, int>::iterator it = map2.begin( ); it != map2.end( ); ++it ) {
cout << it -> first << " => " << it -> second << '\n';
}
return 0;
}
Output:
Before swapping, the map map1 contains the following data :
a => 110
b => 220
c => 330
Before swapping, the map map2 contains the following data :
x => 100
y => 200
After swapping, the map map1 contains the following data :
a => 110
b => 220
c => 330
After swapping, the map map2 contains the following data :
x => 100
y => 200
Explanation:
In this example, we have initialized two maps, map1 and map2, with different key-value pairs and display their contents. After using the map::swap function, the contents of the two maps are exchanged, and the updated data of both maps is displayed using the for loop, which shows that the elements have been successfully swapped.
C++ swap Function Example to Swap Two Maps Using std::swap
Let us take an example to swap the contents of two maps, map1 and map2, using the std::swap in C++.
Example
#include<iostream>
#include<map>
using namespace std; //using standard namespace
int main( ) //main function
{
// Take any two maps
map<int, char> map1;
map<int, char> map2;
// Putting data into map1
map1[1] = 'a';
map1[2] = 'b';
map1[3] = 'c';
map1[4] = 'd';
// Putting data into map2
map2[5] = 'w';
map2[6] = 'x';
map2[7] = 'y';
// // Print the elements of maps before swapping map1 and map2
cout <<"Before swap, map1: \n "<< "\tKEY\tELEMENT\n";
for ( auto it = map1.begin( );
it != map1.end( ); it++ ) {
cout <<"\t" << it -> first << "\t" << it->second << '\n' ;
}
cout <<"Before swap, map1: \n "<< "\tKEY\tELEMENT\n";
for ( auto it = map2.begin( );
it != map2.end( ); it++ ) {
cout <<"\t" << it -> first << "\t" << it->second << '\n' ;
}
// Swap elements of maps
swap( map1, map2 );
// Print the elements of maps after swapping map1 and map2
cout <<"After swap, map1: \n "<< "\tKEY\tELEMENT\n";
for ( auto it = map1.begin( );
it != map1.end( ); it++ ) {
cout <<"\t" << it -> first << "\t" << it->second << '\n' ;
}
cout <<"After swap, map2: \n "<< " \tKEY\tELEMENT \n";
for ( auto it = map2.begin( );
it != map2.end( ); it++ ) {
cout <<"\t" << it -> first << "\t" << it -> second << '\n';
}
return 0;
}
Output:
Before swap, map1:
KEY ELEMENT
1 a
2 b
3 c
4 d
Before swap, map1:
KEY ELEMENT
5 w
6 x
7 y
After swap, map1:
KEY ELEMENT
5 w
6 x
7 y
After swap, map2:
KEY ELEMENT
1 a
2 b
3 c
4 d
Explanation:
In this example, we have initialized two maps, map1 and map2, with integer keys and character values, and display their contents using the for loop. After that, we have performed the swapping of the values where we have swapped both maps with each other using the map swap function. After swapping, we have displayed the data for both the maps using the for loop.
C++ map::swap Example to Swap Maps with String Keys and Integer Values
Let us take an example to swap maps with string keys and integer values using the map::swap function in C++.
Example
#include <iostream>
#include <string>
#include <map>
using namespace std; // using standard namespace
void show(const char *msg, map<string, int> mp);
int main() { // main function
// Initialized map m1 and m2
map<string, int> m1;
map<string, int> m2;
// Inserting data to map1
m1.insert(pair<string, int>("A", 100));
m1.insert(pair<string, int>("G", 300));
m1.insert(pair<string, int>("B", 200));
// m1 and m2 data before swapping
show("Contents of m1 before swapping:", m1);
show("Contents of m2 before swapping (empty):", m2);
// Exchange the contents of m1 and m2.
cout << "Exchange m1 and m2.\n";
m1.swap(m2); // swapping
show("Contents of m2 after swapping:", m2);
show("Contents of m1 after swapping:", m1);
// Clear m1
m1.clear();
if (m1.empty()) cout << "m1 is now empty." << endl;
return 0;
}
// Display the contents of a map<string, int> by using an iterator.
void show(const char *msg, map<string, int> mp) {
cout << msg << endl;
for (auto itr = mp.begin(); itr != mp.end(); ++itr) {
cout << " " << itr->first << " => " << itr->second << endl;
}
cout << endl;
}
Output:
Contents of m1 before swapping:
A => 100
B => 200
G => 300
Contents of m2 before swapping (empty):
Exchange m1 and m2.
Contents of m2 after swapping:
A => 100
B => 200
G => 300
Contents of m1 after swapping:
m1 is now empty.
Explanation:
In this example, we have declared two maps, m1 and m2, with a string as the key type and int as the value type. After that, we have inserted the data into m1, while m2 remained empty, and show their contents using the show function. Next, we use the swap to exchange the contents of m1 and m2. After swapping, m1 became empty and m2 contained the elements of m1. Finally, we called the clear method on m1, and checked if m1.empty, i.e., if the map m1 has no data, then we print the message that it is empty now.
Features of the map::swap function in C++
There are several features of the map::swap function in C++. Some of them are as follows:
- It is used to only swap the internal structures.
- It maintains the iterator validity.
- This function needs two maps that have the same key and value types.
- It is very useful to clear a map by swapping it with an empty map.
Conclusion
In conclusion, the C++ map::swap function is an efficient function. It is commonly used to exchange or swap the content of two maps. It prevents the element-wise copying, handles iterator validity, and effectively clears a map. It is better to choose to swap two maps or reset a map.
C++ map::swap Function FAQs
1) What is the main purpose of the map::swap function in C++?
In C++, the map::swap function is a member function of the STL map container. It is commonly used to swap (or exchange) the contents of two maps, but both maps must be of the same type, although sizes may differ
2) If two maps have different comparators, is it possible to swap them?
No, it is not possible to swap two maps that have different comparators because the comparator type is part of the type of the map. We cannot swap maps with different comparator types because they are different types altogether.
3) Can swapping two maps cause iterator invalidation?
No, iterators, pointers, and references to elements remain valid after swapping, but they now refer to the elements in the other map. It can be tricky if we do not realize that iterators effectively "move" to the other container.
4) Does swapping two maps copy or move elements in C++?
No, swapping does not copy or move individual elements. It only swaps the internal pointers and metadata, so it is a constant-time operation.
5) Can we use the 'swap' function to implement move assignment for a map?
Yes, it is a common idiom for move assignment to swap the current map with the source map, which efficiently transfers ownership of the data. Therefore, we can use the 'swap' function to implement move assignment for a map.