Home >Backend Development >C++ >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; }
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; }
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!