Sorting std::map by Value
Sorting a std::map by value, rather than by key, is a common requirement in various programming scenarios. This article provides an elegant solution to this problem by flipping the key and value pairs in the map using custom template functions.
Custom Template Functions for Flipping Pairs and Maps
The provided solution involves two custom template functions: flip_pair() and flip_map(). The flip_pair() function takes a pair of values and flips them, resulting in a new pair with the swapped values.
template<typename A, typename B> std::pair<B,A> flip_pair(const std::pair<A,B> &p) { return std::pair<B,A>(p.second, p.first); }
The flip_map() function utilizes the flip_pair() function to flip all the key-value pairs in the source map and return a new multimap with the flipped pairs.
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; }
Example Usage
To sort a std::map by value, one can use the flip_map() function to create a new multimap with the flipped pairs. This multimap will be sorted by the former values of the source map.
std::map<int, double> src; ... std::multimap<double, int> dst = flip_map(src); // dst is now sorted by what used to be the value in src!
Generic Associative Source for C 11 and Later
For alternative associative containers to std::map, such as std::unordered_map, a more generic function can be used to handle both std::map and std::unordered_map sources.
// flips an associative container of A,B pairs to B,A pairs 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 function can be used with any associative container that supports the required template parameters, such as std::map, std::unordered_map, and more.
The above is the detailed content of How Can I Efficiently Sort a `std::map` by Value in C ?. For more information, please follow other related articles on the PHP Chinese website!