2012-09-26 57 views
0

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

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

如何迭代第二张图并获得第一个和第二个键/值?

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

我希望有人有一个完整的答案。

回答

3
#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; 
} 
+0

为了公平起见,问题中的代码也没有。 – Martin

+1

@Martin:好的,但是大多数SO问题都是如此。这通常是为什么他们是问题... –

+0

这个问题显然是要求两件事情:你通常如何访问内部地图;以及如何插入新元素。他们没有问及它/它的错字。 – Martin

4

it->second会给你“第二张地图”。只需重复一遍即可。

2

您将需要第二个迭代器在另一个嵌套的for-loop循环遍历it-> second,就像您在mymap上迭代一样。

2

像这样:

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")); 
+0

不能编译 – perreal

+0

是的,但我的意思是使用map :: insert函数。但我非常喜欢你对第一部分所做的一切。谢谢。 :) – user1058431

+0

@perreal:谢谢,修正 - 我在OP的代码中误读了一个'typedef',实际上没有! –

1

在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,所以最好是像这样键入每种类型。无论如何,使用这样的typedefs是个好主意。

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