dnguy104
dnguy104

Reputation: 1

referencing an object using auto iterator

unordered_map<char,int> letter;

for (auto it = letter.begin(); it != letter.end() ; it++) {
    if (it->second) return false;    
}

for (auto it : letter) {
    if (it.second) return false;
}

Above, there are 2 iterator loops which I believe output the same thing. I can understand that the it in the first loop points to the object in the unordered_map, so the second variable must be referenced with ->. But I dont understand how the second loop can do .second. Can anyone explain how to 2nd loop works?

Upvotes: -1

Views: 65

Answers (1)

user2209008
user2209008

Reputation:

The second loop is a range-based for loop. It is not returning an iterator, but is instead returning a copy of the key-value pair (pair<char, int>), so it does not need to ues a -> operator to access the values.

Your range-based for would be equivalent to this, only less verbose, of course.

for (auto it = letter.begin(); it != letter.end() ; it++) {
    auto kvp = *it;
    if (kvp.second) return false;
}

Upvotes: 4

Related Questions