Home >Backend Development >C++ >How Can I Sort an std::map by Value in C ?
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; }
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; }
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!