How do I iterate safely and efficiently with std::map?

When working with std::map in C++, it is important to iterate safely and efficiently. Here, we will demonstrate how to achieve this by using iterators and range-based for loops.

C++, std::map, iteration, iterators, range-based for loop, efficiency
This document explains safe and efficient iteration techniques for std::map, a key-value container in C++. Learn to use iterators and range-based loops effectively.

#include <map>
#include <iostream>

int main() {
    std::map myMap = {
        {1, "Apple"},
        {2, "Banana"},
        {3, "Cherry"}
    };

    // Safe iteration using range-based for loop
    for (const auto &pair : myMap) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }

    // Iterating using iterators
    for (auto it = myMap.begin(); it != myMap.end(); ++it) {
        std::cout << it->first << ": " << it->second << std::endl;
    }

    return 0;
}
    

C++ std::map iteration iterators range-based for loop efficiency