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?
You should use Boost.Bimap for this sort of thing.
I've just done a similar question in my c++ book. The answer I came up with might not be very efficient though:
Create another map, provide a less() function based on the value not key, AND the function should return true if the value1 <= value2 (not strictly < ). In this case, elements with non-distinct values can be sorted as well.
You can’t, by definition. A map is a data structure that sorts its element by key.
Based on @swegi's idea, I implemented a solution in c++11 using a
multimap
:Code on Ideone
I also implemented a C++11 solution based on @Chris' idea using a vector of pairs. For correct sorting, I provide a lambda expression as comparison functor:
Code on Ideone
The first solution is more compact, but both solutions should have roughly the same performance. Inserting into a
multimap
is of O(log n), but this has to be done for n entries, resulting in O(n log n). Sorting the vector in the second solution also results in O(n log n).I also gave a try to @Chris' idea on using a set of pairs. However, it won't work if the values aren't all distinct. Using a functor that compares only the pair's second element doesn't help. If you first insert
make_pair(1, 1)
into the set and then try to insertmake_pair(2, 1)
, then the second pair won't be inserted, because both pairs are seen as identical by that set. You can see that effect here on Ideone.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.