在地图中迭代地图

iterate over map within map

本文关键字:地图 迭代      更新时间:2023-10-16

我在迭代地图中的第二张地图时遇到问题。

#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;
}

您将需要在额外的嵌套 for 循环中提供第二个迭代器来迭代它>秒,就像您在 mymap 上迭代一样。

像这样:

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 是个好主意。

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