問題描述
如何實現 STL 映射按值排序?
How can I implement STL map sorting by value?
例如,我有一個地圖 m
:
For example, I have a map m
:
map<int, int> m;
m[1] = 10;
m[2] = 5;
m[4] = 6;
m[6] = 1;
我想按 m
的值對該地圖進行排序.所以,如果我打印地圖,我想得到如下結果:
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 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.
這篇關于如何按值對 STL 映射進行排序?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!