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++
// C++ Program to Create a Set of Maps #include <iostream> #include <map> #include <set> using namespace std; int main() { // Create a set of maps set<map< int , string> > MySet; // Create maps to insert into the set map< int , string> map1 = { { 1, "C++" }, { 2, "Java" }, { 3, "Python" } }; map< int , string> map2 = { { 4, "DSA" }, { 5, "OS" }, { 6, "DBMS" } }; // Insert the maps into the set MySet.insert(map1); MySet.insert(map2); // Print the set of maps 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; } |
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)
Set of Maps in C++
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) }