繁体   English   中英

遍历地图内的地图

[英]iterate over map within map

我在遍历地图中的第二张地图时遇到问题。

#include <map>

using namespace std;

map<string, map<string, string> > mymap;
map<string, map<string, string> >::iterator itm;
pair<map<string, map<string, string> >::iterator,bool> retm;

for( itm=mymap.begin(); itm!=mymap.end(); ++itm)
{
cout << "first:\t" << it->first << endl;
}

如何遍历第二张地图并获取第一张和第二张键/值?

第二个问题是,如何使用地图附带的“插入”功能“插入”第一张和第二张地图?

我希望有人能提供完整的答案。

it->second将为您提供“第二张地图”。 只是迭代一下。

#include <map>
#include <iostream>
using namespace std;

map<string, map<string, string> > mymap;
map<string, map<string, string> >::iterator itm;
pair<map<string, map<string, string> >::iterator,bool> retm;

int main() {

  /* populate: */
  mymap.insert(make_pair ("something", map<string, string>()));
  mymap["something"].insert(make_pair ("2", "two"));

  /* traverse: */
  for( itm=mymap.begin(); itm!=mymap.end(); ++itm)
  {
    cout << "first:\t" << itm->first << endl;

    for (map<string, string>::iterator inner_it = (*itm).second.begin();
        inner_it != (*itm).second.end(); 
        inner_it++) {
      cout << (*inner_it).first << " => " << (*inner_it).second << endl;
    }   

  }

  return 0;
}

就像在mymap上进行迭代一样,您将需要在另一个嵌套的for循环中使用第二个迭代器在it-> second上进行迭代。

像这样:

typedef std::map<std::string, std::map<std::string, std::string>>::iterator outer_it;
typedef std::map<std::string, std::string>::iterator                        inner_it;

for (outer_it it1 = mymap.begin(); it1 != mymap.end(); ++it1)
{
    for (inner_it it2 = it1->second.begin(); it2 != it1->second.end(); ++it2)
    {
        std::cout << "first: " << it1->first << ", second: " << it2->first
                  << ", value: " << it2->second << std::endl;
    }
}

要插入:

mymap["hello"]["world"] = "foo";

或者,使用insert

mymap["hello"].insert(std::make_pair("world", "foo"));

如果要插入多个值,请仅执行一次外部查找:

std::map<std::string, std::string> & m = mymap["hello"];
m.insert(std::make_pair("world", "foo"));
m.insert(std::make_pair("word",  "boo"));
m.insert(std::make_pair("lord",  "coo"));

在C ++ 11中,您可以这样做:

for (const auto& outerElem: mymap) {
    cout << "First: " << outerElem.first << endl;
    for (const auto& innerElem: outerElem.second) {
        cout << "  First: " << innerElem.first << endl;
        cout << "  Second: " << innerElem.second << endl;
    }
}

在C ++ 03中,您也可以使用BOOST_FOREACH进行此操作。 但是您不能使用auto ,因此最好像这样键入每个类型。 无论如何,使用这样的typedef是一个好主意。

typedef map<string, string> innerMap;
typedef map<string, innerMap> outerMap;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM