如何遍历C ++地图? [英] How can I loop through a C++ map of maps?
本文介绍了如何遍历C ++地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在C ++中遍历std::map
?我的地图定义为:
How can I loop through a std::map
in C++? My map is defined as:
std::map< std::string, std::map<std::string, std::string> >
例如,上面的容器保存这样的数据:
For example, the above container holds data like this:
m["name1"]["value1"] = "data1";
m["name1"]["value2"] = "data2";
m["name2"]["value1"] = "data1";
m["name2"]["value2"] = "data2";
m["name3"]["value1"] = "data1";
m["name3"]["value2"] = "data2";
如何遍历此地图并访问各种值?
How can I loop through this map and access the various values?
推荐答案
Old question but the remaining answers are outdated as of C++11 - you can use a ranged based for loop and simply do:
std::map<std::string, std::map<std::string, std::string>> mymap;
for(auto const &ent1 : mymap) {
// ent1.first is the first key
for(auto const &ent2 : ent1.second) {
// ent2.first is the second key
// ent2.second is the data
}
}
这应该比早期版本干净得多,并避免了不必要的复制.
this should be much cleaner than the earlier versions, and avoids unnecessary copies.
有些人喜欢用引用变量的显式定义替换注释(如果未使用,则会进行优化):
Some favour replacing the comments with explicit definitions of reference variables (which get optimised away if unused):
for(auto const &ent1 : mymap) {
auto const &outer_key = ent1.first;
auto const &inner_map = ent1.second;
for(auto const &ent2 : inner_map) {
auto const &inner_key = ent2.first;
auto const &inner_value = ent2.second;
}
}
这篇关于如何遍历C ++地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文