Is there a way to sort std::map by the data rather than the key? Right now my code duplicates the entire map in to an array just to do this.
Asked
Active
Viewed 1.1k times
5
-
1Guess you need another map with key/value reversed? – Daniel Mošmondor Oct 21 '10 at 23:55
-
Have not found a good solution either. You cannot just swap the map around (as many suggest) because two values could be the same, creating a new map that could have less elements. In fact **it is impossible** to sort a map by value, as a map is sorted by key (hence why it is fast). Even if you try to create a new map that is sorted, by pushing the values in like a vector, you will still end up with a map that is sorted by key!!! The way I implemented into my code was to create sorted vectors for each of the keys and values, and used the vectors in my application. To make the vectors, I first – ryanmartinneutrino Jul 03 '13 at 02:52
-
Possible duplicate of [STL map--> sort by value?](http://stackoverflow.com/questions/2699060/stl-map-sort-by-value) – Ciro Santilli OurBigBook.com Jan 01 '17 at 14:20
-
Possible duplicate of [Sorting std::map using value](https://stackoverflow.com/questions/5056645/sorting-stdmap-using-value) – Baum mit Augen Mar 01 '19 at 18:40
1 Answers
4
As far as I can remember, std::map
will give you the iterator that will go through the items sorted by the key. Only way to go through the sorted items by the value, and still use the map, is to rewrite whole collection to another map, with key and value reversed.

Daniel Mošmondor
- 19,718
- 12
- 58
- 99
-
I found that using a single vector and simply finding stuff was better. – Jookia Oct 22 '10 at 00:33
-
2
-
I point to Oli Charlesworth's answer at http://stackoverflow.com/a/5056797/158371 – Christian Severin Dec 02 '13 at 21:08