我正在阅读此问题的可接受答案C++ Loop through Map
该答案的示例:
for (auto const& x : symbolTable)
{
std::cout << x.first // string (key)
<< ':'
<< x.second // string's value
<< std::endl ;
}
在这种情况下,auto const&
是什么意思?
它声明了一个名为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
。
auto
从代码的上下文中推断变量的类型。在这种情况下,类型将是symbolTable
中包含的任何内容的类型。 const
表示无法(轻松)更改x
的值。 &
表示x
是对对象的引用,而不是对象本身。
将其放在一起,x
是对symbolTable
内部对象的常量引用。