Home >Backend Development >C++ >How Can I Sort a std::map by Value, Not Key?

How Can I Sort a std::map by Value, Not Key?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-05 10:33:10681browse

How Can I Sort a std::map by Value, Not Key?

Sorting std::map by Value

Sorting a std::map by value requires an alternative approach as the standard sort() function only sorts elements by key. To achieve this, consider the following solution:

Flip Key and Value

Create a new multimap that flips the key and value pairs of the original map using the following function:

template<typename A, typename B>
std::multimap<B,A> flip_map(const std::map<A,B> &src)
{
    std::multimap<B,A> dst;
    std::transform(src.begin(), src.end(), std::inserter(dst, dst.begin()), 
                   flip_pair<A,B>);
    return dst;
}

Usage:

After creating the original map (e.g., std::map src), simply flip the map to sort by value:

std::multimap<double, int> dst = flip_map(src);

Generic Associative Source

This solution can be generalized to work with any associative container using variadic templates:

template<typename A, typename B, template<class,class,class...> class M, class... Args>
std::multimap<B,A> flip_map(const M<A,B,Args...>&src)
{
    std::multimap<B,A> dst;
    std::transform(src.begin(), src.end(),
                   std::inserter(dst, dst.begin()),
                   flip_pair<A,B>);
    return dst;
}

This works for both std::map and std::unordered_map as the source of the flip.

The above is the detailed content of How Can I Sort a std::map by Value, Not Key?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn