How do I sort and stable_sort elements with std::unordered_map?

Sorting and stable sorting elements directly from an std::unordered_map in C++ requires first transferring the elements into a different structure, such as a std::vector, since std::unordered_map does not support ordering. Below is an example demonstrating how to sort the elements of an std::unordered_map based on their keys and values.

To sort elements, you can use std::sort for sorting or std::stable_sort for maintaining the relative order of equivalent elements once they are placed in a vector.


#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>

int main() {
    std::unordered_map myMap = {
        {3, "Three"},
        {1, "One"},
        {2, "Two"},
        {4, "Four"}
    };

    // Move elements to a vector
    std::vector<:pair std::string>> vec(myMap.begin(), myMap.end());

    // Sort by keys
    std::sort(vec.begin(), vec.end());
    
    std::cout << "Sorted by keys:" << std::endl;
    for (const auto &pair : vec) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }

    // Stable sort by values
    std::stable_sort(vec.begin(), vec.end(), [](const auto &a, const auto &b) {
        return a.second < b.second;
    });

    std::cout << "Sorted by values:" << std::endl;
    for (const auto &pair : vec) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }

    return 0;
}
    

C++ unordered_map sort stable_sort vector algorithm key-value pairs