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

How Can I Sort an std::map by Value Instead of Key?

DDD
Release: 2024-12-25 05:22:13
Original
336 people have browsed it

How Can I Sort an std::map by Value Instead of Key?

Sorting an std::map by Value

Sorting an std::map by value rather than key can be more complex than sorting by key. Here's an in-depth analysis of the issue and a solution:

Solution 1: Using a Multimap

To sort an std::map by value, we can create a multimap with the values as keys and the keys as values. This allows us to sort by the values, as in the following example:

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

By iterating through the original map and inserting the flipped pairs into the multimap, we essentially invert the key-value relationship and can then sort by the new keys (the original values).

Solution 2: Generic Associative Source (C 11 Required)

For alternative associative containers (e.g., std::unordered_map), we can use the following generic solution:

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 overload works for both std::map and std::unordered_map by using variadic templates to handle different associative container types.

The above is the detailed content of How Can I Sort an std::map by Value Instead of Key?. 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