C++ How To Loop Through a Map
Loop Through a Map
Use a for-each loop to go through all the key/value pairs of a map:
Example
map<string, int> people = {{"John", 32}, {"Adele", 45}, {"Bo", 29}};
for (auto person : people) {
cout << person.first << " is " << person.second << " years old\n";
}
Explanation:
Each element of a map is a pair. person.first is the key (the name), and person.second is the value (the age).
A map keeps its keys sorted, so the names are printed in alphabetical order.