Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort an STL map by value?

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?

like image 795
Charlie Epps Avatar asked Apr 23 '10 13:04

Charlie Epps


People also ask

Can we sort a map based on value?

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.

Is map in STL sorted?

By default, a Map in C++ is sorted in increasing order based on its key.

Can you sort a map by value in C++?

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.


2 Answers

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.

like image 54
Chris Jester-Young Avatar answered Sep 21 '22 05:09

Chris Jester-Young


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.

like image 41
swegi Avatar answered Sep 19 '22 05:09

swegi