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
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!