Storing std map in map

//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;

    }

}

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:

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));

Tags:

C++

Insert

Map

Std