0
0
CppHow-ToBeginner · 3 min read

How to Iterate Map Using Auto in C++

To iterate over a std::map in C++, use a range-based for loop with auto to automatically deduce the type of each element. For example, for (auto &pair : myMap) lets you access each key-value pair easily without writing the full type.
📐

Syntax

Use a range-based for loop with auto to iterate over a std::map. Each element is a std::pair. The syntax is:

for (auto &pair : mapName) {
    // use pair.first for key
    // use pair.second for value
}

Here, auto &pair automatically deduces the type of each map element and uses a reference to avoid copying.

cpp
for (auto &pair : mapName) {
    // Access key with pair.first
    // Access value with pair.second
}
💻

Example

This example shows how to create a std::map of strings to integers and iterate over it using auto. It prints each key and value.

cpp
#include <iostream>
#include <map>

int main() {
    std::map<std::string, int> ages = {
        {"Alice", 30},
        {"Bob", 25},
        {"Charlie", 35}
    };

    for (auto &pair : ages) {
        std::cout << pair.first << " is " << pair.second << " years old.\n";
    }

    return 0;
}
Output
Alice is 30 years old. Bob is 25 years old. Charlie is 35 years old.
⚠️

Common Pitfalls

One common mistake is forgetting to use a reference with auto, which causes copying of each map element and can be inefficient:

for (auto pair : mapName) { /* ... */ }

This copies each std::pair. Use auto &pair to avoid this.

Another pitfall is modifying the key, which is const in std::map pairs and will cause a compile error.

cpp
/* Wrong: copies each pair */
for (auto pair : ages) {
    std::cout << pair.first << " " << pair.second << "\n";
}

/* Correct: uses reference to avoid copying */
for (auto &pair : ages) {
    std::cout << pair.first << " " << pair.second << "\n";
}
📊

Quick Reference

Remember these tips when iterating a std::map with auto:

  • Use auto &pair to avoid copying.
  • Access key with pair.first.
  • Access value with pair.second.
  • Do not modify pair.first as keys are const.

Key Takeaways

Use range-based for loops with auto to iterate maps simply and clearly.
Always use a reference (auto &) to avoid copying map elements.
Access keys with pair.first and values with pair.second.
Map keys are const and cannot be changed during iteration.
auto makes your code cleaner and easier to maintain.