Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 340
KT100 Avatar asked Jan 28 '13 05:01

KT100


2 Answers

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.

like image 149
Karthik T Avatar answered Sep 19 '22 15:09

Karthik T


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

for (auto& [key, value]: mymap) {         std::cout << key << " => " << value << '\n'; }  
like image 23
BoshWash Avatar answered Sep 19 '22 15:09

BoshWash