Set of Maps in C++
Last Updated :
05 Feb, 2024
In C++, Sets are containers that allow the users to store unique elements in sorted order while maps containers store key-value pairs in sorted order based on the keys. In this article, we will discuss how to combine these two containers and create a Set of Maps in C++.
Example
Input:
MySetOfMaps = { { {1, "C++"}, {2, "Java"}, {3, "Python"} },
{ {4, "DSA"}, {5, "OS"}, {6, "DBMS"} } }
Output:
Set Elements:
Map:0 { (1, C++) (2, Java) (3, Python) }
Map:1 { (4, DSA) (5, OS) (6, DBMS) }
Set of Maps in C++ STL
In C++, a set of maps can be created by nesting a std::map container inside the std::set container. We can do this by specifying the elements of the set to be a map in the set declaration.
C++ Program to Create a Set of Maps
C++
#include <iostream>
#include <map>
#include <set>
using namespace std;
int main()
{
set<map< int , string> > MySet;
map< int , string> map1
= { { 1, "C++" }, { 2, "Java" }, { 3, "Python" } };
map< int , string> map2
= { { 4, "DSA" }, { 5, "OS" }, { 6, "DBMS" } };
MySet.insert(map1);
MySet.insert(map2);
cout << "Set Elements: " << endl;
int i = 0;
for ( auto & map : MySet) {
cout << "Map " << i << ": {" ;
for ( auto & pair : map) {
cout << " (" << pair.first << ", "
<< pair.second << ")" ;
}
cout << " }" << endl;
i++;
}
return 0;
}
|
Output
Set Elements:
Map 0: { (1, C++) (2, Java) (3, Python) }
Map 1: { (4, DSA) (5, OS) (6, DBMS) }
Time Complexity: O(N * M) to traverse N maps present in the set where M is the average number of elements in each map.
Auxilary Space : O(1)
Share your thoughts in the comments
Please Login to comment...