21xrx.com
2025-06-26 07:53:15 Thursday
登录
文章检索 我的文章 写文章
C++11 中使用 auto 遍历 map
2023-06-28 07:26:32 深夜i     80     0
C++11 auto 遍历 map

随着 C++11 的到来,auto 这个关键字也得到了大量的增强,成为 C++ 中一个非常重要的工具。在 C++11 中,auto 可以非常方便地用于遍历 map。本文将介绍如何使用 auto 遍历 map。

在 C++11 中,auto 可以用于声明变量时自动推导类型,因此我们可以使用 auto 关键字来快速声明一个迭代器,然后使用这个迭代器来遍历 map。下面是一个简单的例子:

#include <iostream>
#include <map>
#include <string>
int main()
{
  std::map<std::string, int> myMap = {"a", "b", "c"};
  // 使用 auto 声明迭代器
  for (auto it = myMap.begin(); it != myMap.end(); ++it)
  
    std::cout << it->first << " = " << it->second << std::endl;
  
  return 0;
}

在这个例子中,我们使用了 std::map 类型来创建一个字符串-整数的 map。然后我们使用 auto 关键字声明了一个迭代器 it。由于 map 中存储的是键值对,因此迭代器指向的元素也是一个 std::pair 类型的对象。我们使用箭头运算符来访问该元素的键和值,然后输出它们。

当然,对于这种简单的用例,auto 并没有太大的作用。但是当 map 中的类型比较复杂时,auto 就会派上用场。下面是一个稍微复杂一些的例子:

#include <iostream>
#include <map>
#include <string>
#include <vector>
struct Student
  int id;
  std::string name;
  std::vector<int> scores;
;
int main()
{
  std::map<int, Student> students = {{1, {1, "Tom", 92}},
                    {2, {2, "Jerry", 78}},
                    {3, {3, "Alice", 87}}};
  // 使用 auto 声明迭代器
  for (auto it = students.begin(); it != students.end(); ++it)
  {
    std::cout << "ID: " << it->first << std::endl;
    std::cout << "Name: " << it->second.name << std::endl;
    std::cout << "Scores: ";
    for (auto score : it->second.scores)
    
      std::cout << score << " ";
    
    std::cout << std::endl;
  }
  return 0;
}

在这个例子中,我们使用了自定义的 Student 类型作为 map 的 value。这个类型包含一个 int 类型的 id 和一个 std::vector 类型的 scores,其中 scores 存储了该学生的成绩。我们使用 map 类型创建了一个 id-Student 的映射表,然后使用 auto 声明了迭代器 it。在遍历 map 时,我们可以通过 it->first 来访问键,通过 it->second 来访问值,然后遍历 scores 打印每个学生的成绩。

在 C++11 中使用 auto 遍历 map 很方便,而且对于复杂的类型也能正确推导类型,避免了手动指定类型的麻烦。我们可以通过这种方式快速方便地遍历 map,并对每个元素进行处理。

  
  

评论区