【问题标题】:what does `auto const& x ` do in C++?`auto const& x` 在 C++ 中做了什么?
【发布时间】:2020-07-03 08:07:45
【问题描述】:

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

该答案中的一个示例:

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

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

【问题讨论】:

  • 请注意,Stack Overflow 不能很好地替代 good C++ language reference。问题中的所有概念都将在任何好的文本中尽早详细介绍。

标签: c++ iterator auto


【解决方案1】:

这使用range-based for 语句。它声明了一个名为x 的变量,它是容器值类型的对常量的引用。由于symbolTablestd::map&lt;string, int&gt;,因此编译器会为x 分配对映射value_type 的常量引用,即std::pair&lt;const std::string, int&gt;

这相当于std::pair&lt;const std::string, int&gt; const &amp;x,但更短。每当序列的类型发生变化时,它都会自动适应auto

【讨论】:

  • 你对循环在做什么有一个很好的解释,但你没有解释auto 在做什么。你应该添加那个
猜你喜欢
  • 2011-03-11
  • 1970-01-01
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
  • 2011-10-21
  • 2015-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多