Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing std map in map

Tags:

c++

std

insert

map

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?

like image 504
Max Frai Avatar asked Dec 18 '10 16:12

Max Frai


People also ask

How do you put a STD on a map?

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[].

Can we have map inside map in C++?

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.

Can we store pair in map?

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.


5 Answers

Try:

std::map< std::string, std::map<std::string, std::string> > someStorage;

someStorage["Hi"]["This Is Layer Two"] = "Value";
like image 92
Martin York Avatar answered Oct 01 '22 18:10

Martin York


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));
like image 31
Dark Falcon Avatar answered Oct 02 '22 18:10

Dark Falcon


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.

like image 43
TToni Avatar answered Oct 04 '22 18:10

TToni


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

    }

}
like image 32
Gelo Avatar answered Oct 02 '22 18:10

Gelo


Also you can use list initialization:

someStorage.insert( std::make_pair("key", std::map<std::string, std::string> {std::make_pair("key2", "value2")}) );
like image 29
Roma Pavlov Avatar answered Oct 02 '22 18:10

Roma Pavlov