Search code examples
c++dictionarystlhashtable

Is there any C++ function to sort a Hash table?


I want to know that how can I sort an unordered_map in C++ on the basis of its values (Not Keys, as the map can be used for that). I understand that one solution is to copy its values to a vector and then sort that vector. But, Is there any function to do it?


Solution

  • There isn’t a function but it’s a straightforward two-liner:

    auto vec = std::vector<std::pair<TKey, TValue>>(begin(map), end(map));
    std::sort(begin(vec), end(vec), [](auto a, auto b) { return a.second < b.second; });