STL地图 - >排序值?地图、STL、GT

2023-09-10 22:54:43 作者:乏味色情

我不知道我怎么能实现对STL地图按值排序。

I wonder how can I implement the STL map sorting by value.

例如,我有一个图M

map<int, int>;
m[1] = 10;
m[2] = 5;
m[4] = 6;
m[6] = 1;

然后。我想那种带有M的值。 所以,如果我打印地图,我希望得到的结果类似。

and then.. I'd like to sort that with the m's value. So, if I print the map, I'd like to get the result like

m[6] = 1
m[2] = 5
m[4] = 6
m[1] = 10

这一点。

我如何可以排序像这样? 有没有什么办法,我可以用键和值排序的值处理?

How can I sort like 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.