I need to sort an std::map
by value rather than by key. Is there an easy way to do it?
I got one solution from the follwing thread:
std::map sort by data?
Is there a better solution?
map<long, double> testMap;
// some code to generate the values in the map.
sort(testMap.begin(), testMap.end()); // is there any function like this to sort the map?
Flipped structure might no longer be a map but rather a multimap, thus in the flip_map example above not all elements from B will necessarily appear in the resulting data structure.
If you want to present the values in a map in sorted order, then copy the values from the map to vector and sort the vector.
Even though correct answers have already been posted, I thought I'd add a demo of how you can do this cleanly:
Generic Associative Source (requires C++11)
If you're using an alternate to
std::map
for the source associative container (such asstd::unordered_map
), you could code a separate overload, but in the end the action is still the same, so a generalized associative container using variadic templates can be used for either mapping construct:This will work for both
std::map
andstd::unordered_map
as the source of the flip.I needed something similar, but the flipped map wouldn't work for me. I just copied out my map (freq below) into a vector of pairs, then sorted the pairs however I wanted.
You can't sort a
std::map
this way, because a the entries in the map are sorted by the key. If you want to sort by value, you need to create a newstd::map
with swapped key and value.Remember that the double keys need to be unique in
testMap2
or usestd::multimap
.A
std::map
sorted by it's value is in essence astd::set
. By far the easiest way is to copy all entries in the map to a set (taken and adapted from here)One caveat: if the map contains different keys with the same value, they will not be inserted into the set and be lost.