I have to store std::map as value in std::map
std::map< std::string, std::map<std::string, std::string> > someStorage;
How to insert into second(inner) map? I tried with:
someStorage.insert( std::make_pair("key", std::make_pair("key2", "value2")) );
But this throws a lot of errors. What's wrong?
If you want to insert element in std::map - use insert() function, and if you want to find element (by key) and assign some to it - use operator[].
Implementing Multidimensional Map in C++ The key can be of any data type, including those that are user-defined. Multidimensional maps are nested maps; that is, they map a key to another map, which itself stores combinations of key values with corresponding mapped values.
These two can be any C++ container class or user-defined class or some other valid class(capable of holding values). So, you can use pair as a key in a map as follows: map<pair<int,string> , long> mp; mp.
Try:
std::map< std::string, std::map<std::string, std::string> > someStorage;
someStorage["Hi"]["This Is Layer Two"] = "Value";
someStorage["key"].insert(std::make_pair("key2", "value2")));
If you still wanted to use insert on the outer map as well, here is one way to do it
std::map<std::string, std::string> inner;
inner.insert(std::make_pair("key2", "value2"));
someStorage.insert(std::make_pair("key", inner));
A map has a insert method that accepts a key/value pair. Your key is of type string, so that's no problem, but your value is not of type pair (which you generate) but of type map. So you either need to store a complete map as your value or you change the initial map definition to accept a pair as value.
//Try this:
std::map< std::string, std::map<std::string, std::string> > myMap;
myMap["key one"]["Key Two"] = "Value";
myMap["Hello"]["my name is"] = "Value";
//To print the map:
for( map<string,map<string,string> >::const_iterator ptr=myMap.begin();ptr!=myMap.end(); ptr++) {
cout << ptr->first << "\n";
for( map<string,string>::const_iterator eptr=ptr->second.begin();eptr!=ptr->second.end(); eptr++){
cout << eptr->first << " " << eptr->second << endl;
}
}
Also you can use list initialization:
someStorage.insert( std::make_pair("key", std::map<std::string, std::string> {std::make_pair("key2", "value2")}) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With