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

标签 c++ loops dictionary iteration idioms

如何在 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 - 我想搜索字符串 s 中字符串 str 的元素,但是当我尝试搜索字符串 s 中的任何内容(例如 str[1])时,它返回 0

python - 在速度方面改进 python 代码

C++ peek() 看不到换行符

c++ - 仅给出一个遍历时查找二叉树的其他两个遍历

r - 获取通过重采样计算的多重回归系数值

excel - 跳过类型不匹配

python - 初始化一个字典,其中每个项目都是空的唯一列表的列表

python - Django / python : error when get value from dictionary

c++ - 在 dft 之后是否有进一步的步骤来计算相位?