C++遍历std::map<std::string, int>方法详解

在C++中,std::map是一个常用的关联容器,用于存储键值对。当我们需要遍历std::map中的所有元素时,可以使用迭代器来实现。

以下是一个在Linux下使用C++遍历std::map<std::string, int>的示例代码:

#include <iostream>
#include <map>

int main() {
  std::map<std::string, int> map_absFilename;

  // 添加一些键值对到map中
  map_absFilename['file1.txt'] = 10;
  map_absFilename['file2.txt'] = 20;
  map_absFilename['file3.txt'] = 30;

  // 使用迭代器遍历map
  std::map<std::string, int>::iterator it;
  for (it = map_absFilename.begin(); it != map_absFilename.end(); ++it) {
    std::cout << 'Key: ' << it->first << ', Value: ' << it->second << std::endl;
  }

  return 0;
}

代码解释:

  1. 首先,我们创建一个std::map<std::string, int>类型的map对象map_absFilename,用于存储文件名和对应整数值的键值对。
  2. 然后,我们使用map_absFilename['key'] = value;的方式向map中添加了三个键值对。
  3. 接下来,我们使用迭代器进行遍历。
    • 首先,创建一个std::map<std::string, int>::iterator类型的迭代器it
    • 使用it = map_absFilename.begin();将迭代器it初始化为指向map的第一个元素。
    • 使用it != map_absFilename.end();作为循环条件,表示迭代器没有到达map的末尾。
    • 在每次循环中:
      • 通过it->first获取当前键值对的键(文件名)。
      • 通过it->second获取当前键值对的值(整数值)。
      • 将键和值打印到控制台。
    • 最后,通过++it将迭代器移动到下一个元素,继续下一次循环,直到遍历完整个map。

总结:

通过使用迭代器,我们可以方便地遍历std::map中的所有元素,并访问每个键值对的键和值。

C++遍历std::map<std::string, int>方法详解(附代码示例)

原文地址: https://www.cveoy.top/t/topic/eYGM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录