C++ 在地图中存储标准地图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4479017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:30:12  来源:igfitidea点击:

Storing std map in map

c++mapinsertstd

提问by Max Frai

I have to store std::map as value in std::map

我必须将 std::map 作为值存储在 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?

但这会引发很多错误。怎么了?

回答by Martin York

Try:

尝试:

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

someStorage["Hi"]["This Is Layer Two"] = "Value";

回答by Dark Falcon

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

回答by TToni

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 notof type pair (which you generate) but of type map. So you either need to store a complete map as your value oryou change the initial map definition to accept a pair as value.

映射具有接受键/值对的插入方法。你的键是字符串类型,所以没问题,但你的值不是类型对(你生成的)而是类型映射。因此,您要么需要将完整的地图存储为您的值,要么更改初始地图定义以接受一对作为值。

回答by Gelo

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

    }

}

回答by Roma Pavlov

Also you can use list initialization:

您也可以使用列表初始化:

someStorage.insert( std::make_pair("key", std::map<std::string, std::string> {std::make_pair("key2", "value2")}) );