`auto const& x ` 在 C++ 中有什么作用?

har*_*uhi 1 c++ iterator auto

我正在阅读这个问题的公认答案C++ Loop through Map

该答案中的一个示例:

for (auto const& x : symbolTable)
{
  std::cout << x.first  // string (key)
            << ':' 
            << x.second // string's value 
            << std::endl ;
}
Run Code Online (Sandbox Code Playgroud)

auto const&在这种情况下是什么意思?

rem*_*s4e 6

这使用基于范围的 for语句。它声明了一个名为 的变量x,它是对容器值类型的const 的引用。由于symbolTable是 a std::map<string, int>,编译器分配给x映射的 的 const 引用value_type,即std::pair<const std::string, int>

这相当于std::pair<const std::string, int> const &x,但更短。auto只要序列的类型发生变化,它就会自动适应。