`auto const&x`在C ++中做什么?

问题描述 投票:0回答:1

我正在阅读此问题的可接受答案C++ Loop through Map

该答案的示例:

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

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

c++ iterator auto
1个回答
1
投票

它声明了一个名为x的变量,它是由编译器确定的对类型的引用。

编译器将序列中元素的类型分配给x(在此假定为std::pair<std::string, std::string>)。有关基于范围的for循环的更多信息,请参见https://en.cppreference.com/w/cpp/language/range-for

这等效于std::pair<std::string, std::string> const &x,但更短。每当序列类型更改时,它都会自动适应auto


0
投票

auto从代码的上下文中推断变量的类型。在这种情况下,类型将是symbolTable中包含的任何内容的类型。 const表示无法(轻松)更改x的值。 &表示x是对对象的引用,而不是对象本身。

将其放在一起,x是对symbolTable内部对象的常量引用。

© www.soinside.com 2019 - 2024. All rights reserved.