5.4.3 Iterating Through a Map

Like sets, maps do not save values by an index, so iterating through a map can only be done via an iterator. Maps iterate in a sort order based on the key.

Map For Loop

The map for loop looks very similar to the set for loop. The main difference is that once you get the iterator value, it returns a pair that needs to be accessed a little differently.

Here is an example using our catalog map from the earlier example.

map<string, double> catalog {{"treats", 3.99}, {"leash", 8.99}, {"crate", 24.99}};

for (map<string, double>::iterator itr = catalog.begin(); itr != catalog.end(); itr ++) {
    cout << "Key: " << itr->first << endl;
    cout << "Value: " << itr->second << endl;
}

Notice in this example how the basic structure of the for loop is the same as you saw with sets. The iterator is declared and initialized to the beginning of your map, then the loop continues until the iterator reaches the end, incrementing up each time.

The difference here is that you need to access a pair of values instead of just one like you saw with sets. To get the key, you access the first element of the pair, and the value is in the second element of the pair.

Just like in sets, you need to dereference the value using a *, then use the dot operator, . to access the value. For example, you could access the value like this: (*itr).first.

Since accessing a dot member for a dereference value is common, C++ has an arrow shortcut, which you see above. Instead of using the star, parenthesis, and dot, you can use -> as a shortcut.

// Equivalent expressions
key = (*itr).first;
key = itr->first;

You will seldom see the former version used and this course will exclusively use the latter.

Find Function in Maps

As you have seen in other data structures, maps have a find function that will return an iterator position of a key in the map. While the iterator position is not particularly useful, it can be useful when compared to the map’s end position.

Here is an example.

if (catalog.find("leash") != catalog.end()) {
    // key found
}
else {
    // key not found
}

Remember from the last example, if you try to access a key that is not found using the at function, you will get an error. If you try to access a key that is not found using the [ ] operator, you will insert a new value into the map, which may not be desired. Using the find function can help you avoid unintended consequences.

Last updated