In C++, a map can be converted to a set of pairs. This can be useful when you want to create a set of pairs from a map, where each pair contains a key and a value. In this article, we will learn how to convert a map to a set of pairs in C++.
Example
Input: myMap = {{1, “one”}, {2, “two”}, {3, “three”}}; Output: Set of Pairs is : {(1, “one”), (2, “two”), (3, “three”)}
Convert Map into Set of Pairs in C++
To convert a std::map to a std::set of std::pair, we can use the range constructor of std::set that takes two iterators, one pointing to the beginning and the other to the end of the map.
C++ Program to Convert Map into Set of Pairs in C++
The below example demonstrates the use of the range constructor to convert a map to a set of pairs in C++ STL.
// C++ program to show how to convert a map to a set of
// pairs
#include <iostream>
#include <map>
#include <set>
using namespace std;
int main()
{
// Creating a map
map<int, string> myMap
= { { 1, "one" }, { 2, "two" }, { 3, "three" } };
// Converting the map to a set of pairs
set<pair<int, string> > mySet(myMap.begin(),
myMap.end());
// Printing the set of pairs
for (auto& pair : mySet) {
cout << "(" << pair.first << ", " << pair.second
<< ")" << endl;
}
return 0;
}
Output
(1, one) (2, two) (3, three)
Time Complexity: O(N log N), where N is the size of the map.
Auxiliary Space: O(N)