In C++, maps, vectors, and sets all are the data storage containers that are provided by the C++ STL. We can nest these containers to create a more complex data structure. In this article, we will explore how to create a Map with vectors as keys and sets as values in C++.
Example
Input: myVector1 = {1, 2, 3} myVector2 = {4, 5, 6} myVector3 = {7, 8, 9} mySet1 = {"Geek", "for", "Geeks"} mySet2 = {"C","C++","Java"} mySet3 = {"AI","ML","Data Science"} Output: myMap = { {{1, 2, 3}: {"Geek", "for", "Geeks"}}, {{4, 5, 6}: {"C","C++","Java"}}, {{7, 8, 9}: {"AI","ML","Data Science"}} }
Map with Vectors as Keys and Sets as Values in C++
To create a map with vectors as keys and sets as values, we first declare the map of type as shown below:
Syntax:
Map<vector<data_Type>, set<data_Type>> myMap
The we can insert the set with its vector one by one.
C++ Program to Create a Map with Vectors as Keys and Sets as Values
// C++ Program to show how to Create a Map with Vectors as // Keys and Sets as Values #include <iostream> #include <map> #include <set> #include <vector> using namespace std;
int main()
{ // Initialzie the map with vector keys and set values
map<vector< int >, set<string> > myMap;
// Create the vectors which will act as keys in the map
vector< int > v1 = { 1, 2, 3 };
vector< int > v2 = { 4, 5, 6 };
vector< int > v3 = { 7, 8, 9 };
// Create the sets which will act as values in the map
set<string> s1 = { "Geek" , "for" , "Geeks" };
set<string> s2 = { "C" , "C++" , "Java" };
set<string> s3 = { "AI" , "ML" , "Data Science" };
// Insert key-value pairs into the map
myMap[v1] = s1;
myMap[v2] = s2;
myMap[v3] = s3;
// Print key-value pairs of the map
for ( const auto & pair : myMap) {
cout << "Key: " ;
for ( int key : pair.first) {
cout << key << " " ;
}
cout << " Value: {" ;
for ( const string& value : pair.second) {
cout << value << ", " ;
}
cout << "}" << endl;
}
return 0;
} |
Key: 1 2 3 Value: {Geek, Geeks, for, } Key: 4 5 6 Value: {C, C++, Java, } Key: 7 8 9 Value: {AI, Data Science, ML, }
Time Complexity: O(N) where N is the number of pairs in the map.
Auxiliary Space: O(N*(M+K)) where N is the number of key-value pairs in the map , M is the average size of the vectors used as keys and K is the average size of the sets uses as values.