Home > Backend Development > C++ > How Can I Sort an std::map by Value in C ?

How Can I Sort an std::map by Value in C ?

DDD
Release: 2024-11-30 19:01:12
Original
1004 people have browsed it

How Can I Sort an std::map by Value in C  ?

Sorting an std::map by Value

Question: How can I effortlessly sort an std::map based on its values?

Answer:

Traditional Approach (Prior to C 11)

Prior to the introduction of C 11, sorting a map by values required an intermediary step of converting the std::map into a std::pair. This involved using a custom sorting function and manually specifying the comparison parameters.

C 11 Approach

With the advent of C 11, a cleaner solution emerged. The following code snippet demonstrates how:

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;
}
Copy after login

This function effectively flips the key-value pairs within the map, allowing you to iterate over the sorted values.

Generic Associative Source (C 11 and Above)

For more flexibility, a generic version of the flipping function can be created, allowing it to work with any associative container:

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;
}
Copy after login

This function takes any associative container class as input, making it convenient for use with both std::map and std::unordered_map.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template