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.
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'; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With