如何在 C++ 中遍历 std::map
?我的 map 定义为:
std::map< std::string, std::map<std::string, std::string> >
例如,上面的容器保存这样的数据:
m["name1"]["value1"] = "data1";
m["name1"]["value2"] = "data2";
m["name2"]["value1"] = "data1";
m["name2"]["value2"] = "data2";
m["name3"]["value1"] = "data1";
m["name3"]["value2"] = "data2";
如何循环遍历此 map 并访问各种值?
最佳答案
老问题,但其余答案自 C++11 起已过时 - 您可以使用 ranged based for loop并简单地做:
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
}
}
这应该比早期版本更干净,并避免不必要的复制。
有些人喜欢用引用变量的明确定义替换注释(如果未使用,这些变量会被优化掉):
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++ - 如何循环遍历 map 的 C++ map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4844886/