Search code examples
c++iteratorauto

what does `auto const& x ` do in C++?


I'm reading the accepted answer to this question C++ Loop through Map

An example in that answer:

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

What does auto const& mean in this case?


Solution

  • This uses a range-based for statement. It declares a variable named x, which is a reference-to-const of the value type of the container. Since symbolTable is a std::map<string, int>, the compiler assigns to x a const reference to the map's value_type, which is std::pair<const std::string, int>.

    This is equivalent to std::pair<const std::string, int> const &x, but shorter. And it will adapt automatically whenever the type of the sequence is changed.