c++dictionaryc++11auto

Implications of using "auto" to iterate over a C++ std::map data structure


So far I have always used an iterator for traversing through all the keys in a 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.


Solution

  • 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.