Is it possible for a map to have two maps as a key and value in C++?
Hi I'm trying to have a map of a sort like map<map<string,string>,map<int,int>>. Is it possible to have such a map in C++..? Or is the concept incorrect..? Using this method to have something like a cricket players status - name, designation, runs and wickets. The code I've pasted is something I tried, it's incorrect.
map<map<string,string>,map<int,int>> m;
map<map<string,string>,map<int,int>>::iterator itr;
map<int,int>::iterator ptr;
m.insert(make_pair("string1","string2"),map<int,int>());
m["string1"].insert(make_pair(10,20));
for(itr = m.begin();itr!=m.end();itr++) {
for (ptr = itr->second.begin(); ptr != itr->second.end(); ptr++) {
cout << "First key is " << itr->first<< " And second key is " << ptr->first<< " And value is " << ptr->second << endl;
}
}
All feedback is greatly appreciated, thanks!
Solution 1:
Is it possible for a map to have two maps as a key and value in C++?
Yes, it is. There aren't many restrictions on the value type. Primary restriction on the key is that it must be orderable by the provided comparator (std::less<Key>
by default). std::map
does satisfy those requirements given appropriate key and value types.
m.insert(make_pair("string1","string2"),map<int,int>());
This isn't correct. You cannot pass the value as a separate argument to insert
. Furthermore you cannot initialise the key that is a map using a pair. Here is a correct example:
std::map<std::string, std::string> key {
{"string1", "string2"},
};
// not needed since operator[] will insert a value initialised element
// m.emplace(key, std::map<int,int>{});
m["string1"].insert(make_pair(10, 20));
This isn't correct. The key of the map is another map, and a string cannot be compared to a map, so this lookup cannot work. In this corrected example:
m[key].emplace(10, 20);
cout << "First key is " << itr->first<< " And second key is " << ptr->first<< " And value is " << ptr->second << endl;
This won't work since you cannot insert a map (that is the key) into a character stream. You could write something like this for example:
for (auto& [key, value] : m) {
std::cout << "key: ";
for (auto& [key_key, key_value] : key) {
std::cout
<< "key of key is " << key_key
<< " value of key is " << key_value
<< ", "
;
}
std::cout << "\nvalue: ";
for (auto& [value_key, value_value] : value) {
std::cout
<< "key of value is " << value_key
<< " value of value " << value_value
<< ", "
;
}
std::cout << "\n\n";
}
However, it's quite rare for map to be a useful key of a map, and considering your mistaken use of your map, I suspect that you actually need the key to be a string rather than a map.