How to iterate over a C++ STL map data structure using the 'auto' keyword?

This code uses 2 new features from C++11 standard the auto keyword, for type inference, and the range based for loop.

Using just auto this can be written as (thanks Ben)

for (auto it=mymap.begin(); it!=mymap.end(); ++it)

Using just range for this can be written as

for (std::pair<const char,int>& x: mymap) {
        std::cout << x.first << " => " << x.second << '\n';
}  

Both of these do the exact same task as your two versions.


In addition to the previous answers, C++17 added another approach using structured bindings:

for (auto& [key, value]: mymap) {
        std::cout << key << " => " << value << '\n';
} 

The following worked for me:

for (auto x: mymap) {
  cout << x.first << endl;
}

I am curious to know the exact implications of using the keyword "auto" here.

It enables:

  • Less typing for a typical iterating code
  • Less chances of manual errors because compiler deduces the exact type of the iterator.