How to Convert a Map of Set of Pairs in C++?
Last Updated :
29 Feb, 2024
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++
#include <iostream>
#include <map>
#include <set>
using namespace std;
int main()
{
map< int , string> myMap
= { { 1, "one" }, { 2, "two" }, { 3, "three" } };
set<pair< int , string> > mySet(myMap.begin(),
myMap.end());
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)
Share your thoughts in the comments
Please Login to comment...