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

Iterating through a `std::unordered_map` in C++ can be done efficiently using range-based for loops or iterators. Below is an example demonstrating how to safely and efficiently iterate through the entries of an `std::unordered_map`.

Keywords: C++, unordered_map, iteration, range-based for loop, iterators
Description: This guide provides an overview of safe and efficient iteration methods for `std::unordered_map` in C++, helping developers to manage key-value pairs effectively.
#include <iostream>
#include <unordered_map>

int main() {
    std::unordered_map<std::string, int> myMap = {
        {"apple", 1},
        {"banana", 2},
        {"orange", 3}
    };

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

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

    return 0;
}
    

Keywords: C++ unordered_map iteration range-based for loop iterators