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

When working with a std::multimap in C++, it's essential to iterate through the elements safely and efficiently. A std::multimap is a container that allows multiple elements to have the same key, making it useful for situations where duplicates are necessary. Here’s an example on how to do this effectively.


#include <iostream>
#include <map>

int main() {
    // Create a multimap
    std::multimap myMultimap;

    // Insert some values
    myMultimap.insert(std::make_pair(1, "Apple"));
    myMultimap.insert(std::make_pair(2, "Banana"));
    myMultimap.insert(std::make_pair(1, "Apricot"));
    myMultimap.insert(std::make_pair(3, "Cherry"));

    // Safe iteration using const_iterator
    for (auto it = myMultimap.cbegin(); it != myMultimap.cend(); ++it) {
        std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
    }

    return 0;
}
    

C++ std::multimap iteration programming containers C++ Standard Library