48

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.

KT100
  • 1,381
  • 5
  • 17
  • 27

6 Answers6

50

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.

John Simoes
  • 601
  • 1
  • 7
  • 18
Karthik T
  • 31,456
  • 5
  • 68
  • 87
  • 1
    And the intermediate version would be `for (auto it=mymap.begin(); it!=mymap.end(); ++it)` – Ben Voigt Jan 28 '13 at 05:08
  • 1
    What's the benefit of using 'auto' here? – KT100 Jan 28 '13 at 05:11
  • 3
    You dont need to type as much. With less boilerplate, the code should become more readable. – Karthik T Jan 28 '13 at 05:12
  • 1
    @KT100 basically at the statement `auto it=mymap.begin()` the compiler will automatically infer that `it` is the iterator type for `mymap` and set the appropriate type, without you needing to figure it out and type it. – Karthik T Jan 28 '13 at 05:14
  • The "just range" loop won't work as posted, as `map::value_type` is `pair`. – JoergB Jan 28 '13 at 06:02
  • 1
    @KT100 This was a good example of the advantages of `auto` :P I wouldnt have messed it up. – Karthik T Jan 28 '13 at 06:04
35

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

for (auto& [key, value]: mymap) {
        std::cout << key << " => " << value << '\n';
} 
BoshWash
  • 5,320
  • 4
  • 30
  • 50
16

The following worked for me:

for (auto x: mymap) {
  cout << x.first << endl;
}
mcsilvio
  • 1,098
  • 1
  • 11
  • 20
5

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.
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • https://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/ This explains why you should (almost) always use auto. – Tolli Apr 26 '16 at 19:57
3

It's new feature of C++11, it's called Range-Based for Loops, which iterates over all elements of a given range, array, or collection. It’s what in other programming languages would be called a foreach loop The general syntax is as follows:

for ( decl : coll ) {
    statement
}

Auto: Automatic Type Deduction with auto

With C++11, you can declare a variable or an object without specifying its specific type by using, for example:

auto i = 42; // i has type int
double f();
auto d = f(); // d has type double
billz
  • 44,644
  • 9
  • 83
  • 100
  • You can find more information and examples of range-based for loops here: http://en.cppreference.com/w/cpp/language/range-for – Tolli Apr 26 '16 at 19:54
0
for (auto& x: mymap) {
        std::cout << x.first << " => " << x.second << '\n';
}  

In this code basically two things are used -

First - auto keyword :

The auto keyword specifies that the type of the variable that is being declared will be automatically deducted from its initializer.

We can use auto keyword when we are not sure about type of variable we are going to work on and can be used to iterate over a map, list using an auto variable or iterator in which we didn't know the elements type which are present inside map, list etc.

Second - range based loops- This form of for loop called the “range-based for”, will iterate over each element in the map given in code.

so in our code - We are iterating our map whose elements value type we didn't know by using auto and here we do not need to know the size of map provided to us as we have used range based loops by help of which we will iterate over each element present in the map.