c++ - 如何循环遍历 map 的 C++ map ?

如何在 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/

相关文章:

c++ - 单引号在 C++ 中用于多个字符时有什么作用?

c++ - 如何检查元素是否在 std::set 中?

c++ - C/C++ 中字符的大小 ('a' )

c++ - 用 C 或 C++ 为 Android 编写应用程序?

c++ - 类成员函数模板可以是虚拟的吗?

c++ - 在现代 C++11/C++14/C++17 和 future 的 C++20 中枚举到字

c++ - 将二维数组传递给 C++ 函数

c++ - 为什么 C++ 编译器不定义 operator== 和 operator!=?

c++ - C++单元测试框架比较

c++ - 以理智、安全和有效的方式复制文件