0
0
CppHow-ToBeginner · 3 min read

How to Iterate Over Map in C++: Syntax and Examples

To iterate over a std::map in C++, use a range-based for loop with auto to access each key-value pair, or use iterators with a traditional loop. Each element is a std::pair where first is the key and second is the value.
📐

Syntax

You can iterate over a std::map using either a range-based for loop or iterators.

  • Range-based for loop: Automatically loops over each element.
  • Iterator loop: Uses begin() and end() to manually move through the map.

Each element is a std::pair<const KeyType, ValueType> where first is the key and second is the value.

cpp
for (const auto& pair : myMap) {
    // use pair.first (key) and pair.second (value)
}

for (auto it = myMap.begin(); it != myMap.end(); ++it) {
    // use it->first (key) and it->second (value)
}
💻

Example

This example shows how to create a std::map of strings to integers and print all key-value pairs using a range-based for loop.

cpp
#include <iostream>
#include <map>

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

    for (const 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

Common mistakes when iterating over a map include:

  • Modifying the map while iterating, which can invalidate iterators.
  • Using non-const references in range-based loops when you don't intend to modify elements.
  • Confusing pair.first (key) with pair.second (value).

Always use const auto& in range-based loops if you only need to read the map.

cpp
/* Wrong: Modifying map during iteration can cause errors */
for (auto it = myMap.begin(); it != myMap.end(); ) {
    if (it->first == "keyToRemove") {
        myMap.erase(it); // This invalidates iterator and causes crash
        break; // prevent further use of invalidated iterator
    } else {
        ++it;
    }
}

/* Right: Use iterator returned by erase to continue safely */
for (auto it = myMap.begin(); it != myMap.end(); ) {
    if (it->first == "keyToRemove") {
        it = myMap.erase(it); // erase returns next valid iterator
    } else {
        ++it;
    }
}
📊

Quick Reference

Summary tips for iterating over std::map:

  • Use for (const auto& pair : map) for simple read-only iteration.
  • Use iterators for more control, especially if you need to modify or erase elements.
  • Remember pair.first is the key, pair.second is the value.
  • Do not modify the map structure while iterating without careful iterator management.

Key Takeaways

Use range-based for loops with const auto& to easily iterate over map key-value pairs.
Each element in a map is a pair where first is the key and second is the value.
Avoid modifying the map while iterating unless you handle iterators carefully.
Iterators give more control but require careful increment and erase handling.
Use const references in loops when you only need to read map contents.