在地图中迭代地图
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;
}
您将需要在额外的嵌套 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;
相关文章:
- C++以迭代方式搜索混合类型地图
- 如何使用迭代器初始化地图的键字段?
- 通过迭代器打印出地图的值
- 迭代C 地图键
- C++同一地图上的嵌套迭代器?
- 为什么当我尝试在地图中迭代时我的值不显示
- C 通过指针的地图进行迭代
- 减去地图迭代器
- 如何在地图迭代器中检测最后一个元素
- 通过地图和打印内容迭代时,倒出输出
- 为什么我的地图迭代器中存在语法错误
- 迭代地图和擦除元素
- 通过C 地图周期性迭代,程序崩溃
- 默认构造的地图迭代器以增量进入无限环路 - 绿色山丘编译器
- C STL,我想知道地图中的双向迭代器和操作员[]之间有什么不同
- C 地图 - 自引用迭代器
- 使用迭代器将值插入嵌套地图
- 如何使用迭代器更新地图的第二个值
- 在地图迭代器上不支持非仿制地图上的平等运算符(==)
- 包装地图迭代器的地图