In C++, maps are data structures found within the Standard Template Library. They are employed to hold elements in key-value pairs, with the sorting of values being determined by the keys themselves.
In C++, the map::swap method belongs to the STL map container. It is frequently employed to interchange the contents of two maps, provided they are of the same type, even if their sizes vary. This function is particularly handy when there is a need to substitute a map with another one or transfer data between two maps without the need to copy elements one by one.
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's consider a scenario where we exchange the elements between two maps by utilizing the map swap method 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 instance, we showcase the utilization of the map::swap method in C++. Initially, we populated m1 with key-value pairs and established an empty map named m2. Upon invoking the m2.swap(m1) operation, the data within m1 and m2 are interchanged, resulting in m1 becoming empty while m2 now holds all the elements that were originally present in m1.
C++ map::swap Example to Swap Two Maps with Different Data
Let's consider an illustration where we interchange the contents of two maps, map1 and map2, utilizing the map::swap method 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 instance, we've created two maps, namely map1 and map2, each containing distinct key-value pairs, and showcased their contents. Following the utilization of the map::swap method, the key-value pairs within the two maps have been interchanged. Subsequently, the revised data of both maps is exhibited through a for loop, confirming the successful swapping of elements.
C++ swap Function Example to Swap Two Maps Using std::swap
Let's consider a scenario where we exchange the contents of two maps, map1 and map2, by employing the std::swap function 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 illustration, we've instantiated two hash maps, map1 and map2, containing integer keys and character values. We then showcase their contents by iterating through them with a for loop. Subsequently, we execute a value-swapping operation where we interchange the contents of both maps utilizing the map swap method. Following the swapping process, we exhibit the data stored in both maps using a for loop.
C++ map::swap Example to Swap Maps with String Keys and Integer Values
Let's consider an instance where we exchange maps containing string keys and integer values by employing the map::swap method 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 illustration, we initialized two maps, m1 and m2, both configured with a string as the key type and integer as the value type. Subsequently, we added data into m1, while m2 remained devoid of any elements, and displayed their contents by utilizing the show function. Following that, we employed the swap function to interchange the contents of m1 and m2. Post swapping, m1 was left devoid of elements, and m2 encapsulated the data that was formerly in m1. To conclude, we invoked the clear method on m1 and assessed m1.empty, indicating whether map m1 is devoid of data, and if so, we output a message affirming that it is currently empty.
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 summary, the C++ map::swap method is a highly effective function. It is frequently employed to interchange or swap the data of two maps. This function avoids copying elements one by one, manages the validity of iterators, and efficiently empties a map. Opting to swap two maps or reset a map is the preferable choice.
C++ map::swap Function FAQs
The primary goal of the map::swap function in C++ is to exchange the elements of two maps.
In C++, the map::swap function belongs to the STL map container as a member function. It is frequently employed to exchange the contents of two maps, with the requirement that both maps are of the same type, even if their sizes differ.
Swapping two maps with different comparators is not possible in Java.
No, exchanging two maps with distinct comparators is not feasible due to the comparator type being integral to the map type. It is impossible to swap maps that have different comparator types as they are essentially distinct types.
Swapping two maps can potentially invalidate iterators.
No, iterators, pointers, and references to elements remain valid after swapping, but they now point to the elements in the other map. This situation can be challenging if one overlooks the fact that iterators essentially transition to the other container.
Swapping two maps in C++ involves the exchange of elements between the two containers without the need to copy or move the elements themselves.
No, exchanging elements does not duplicate or transfer individual elements. It simply interchanges the internal pointers and metadata, making it an operation that takes constant time.
5) Is it possible to utilize the 'swap' function to carry out move assignment for a map data structure?
Yes, it is a typical practice in move assignment to interchange the existing map with the source map, effectively transferring data ownership. Consequently, we can employ the 'swap' method to facilitate move assignment for a map.