How can I implement STL map sorting by value?
For example, I have a map m
:
map<int, int> m; m[1] = 10; m[2] = 5; m[4] = 6; m[6] = 1;
I'd like to sort that map by m
's value. So, if I print the map, I'd like to get the result as follows:
m[6] = 1 m[2] = 5 m[4] = 6 m[1] = 10
How can I sort the map in this way? Is there any way that I can deal with the key and value with sorted values?
In Java, sorting HashMap by values is complicated because there is no direct method available. If we need to sort the HashMap by values, we should create a Comparator. It compares two elements based on the values. After that get the Set of elements from the Map and convert Set into the List.
By default, a Map in C++ is sorted in increasing order based on its key.
Use std::vector and std::sort Algorithm to Sort Map Elements by Value in C++ std::map is an associative container that can store key-value pairs with unique keys, and the latter are used to sort the elements in the object automatically.
Dump out all the key-value pairs into a set<pair<K, V> >
first, where the set
is constructed with a less-than functor that compares the pair's second value only. That way, your code still works even if your values aren't all distinct.
Or dump the key-value pairs into a vector<pair<K, V> >
, then sort that vector with the same less-than functor afterwards.
You can build a second map, with the first map's values as keys and the first map's keys as values.
This works only if all values are distinct. If you cannot assume this, then you need to build a multimap instead of a map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With