1

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?

haruhi
  • 177
  • 1
  • 13
  • 1
    Note that Stack Overflow is a poor replacement for a [good C++ language reference](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). All of the concepts in the question will be covered in detail early on in any good text. – user4581301 Mar 22 '20 at 19:20

1 Answers1

9

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.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
rems4e
  • 3,112
  • 1
  • 17
  • 24
  • 1
    You have a pretty good explanation for what the loop is doing, but you are not explaining what `auto` is doing. You should add that – Remy Lebeau Mar 22 '20 at 21:04