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

KT100 picture KT100 · Jan 28, 2013 · Viewed 82k times · Source

So far I have always used an iterator for traversing through all the keys in an STL map as follows:

    for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it){
            std::cout << it->first << "  => " << it->second << '\n';
    }

Very recently though I came across some code that used a different style to iterate through the keys as shown below. Has this feature been added only recently in revised standard? It seems like a rather interesting way of getting more done with lesser code, as many other languages already provide.

    for (auto& x: mymap) {
            std::cout << x.first << " => " << x.second << '\n';
    }  

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

Answer

Karthik T picture Karthik T · Jan 28, 2013

This code uses 2 new features from the latest C++ standard (C++11) 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.