问题描述
我需要按值而不是键对 std::map
进行排序.有什么简单的方法吗?
I need to sort an std::map
by value rather than by key. Is there an easy way to do it?
我从以下线程中得到了一个解决方案:
std::map 按数据排序?
有更好的解决方案吗?
I got one solution from the follwing thread:
std::map sort by data?
Is there a better solution?
推荐答案
即使正确答案已经发布,我还是想添加一个演示,说明如何干净利落地做到这一点:
Even though correct answers have already been posted, I thought I'd add a demo of how you can do this cleanly:
<小时>
通用关联源(需要 C++11)
如果您为源关联容器使用 std::map
的替代品(例如 std::unordered_map
),您可以编写一个单独的重载,但最终动作还是一样的,所以使用可变参数模板的广义关联容器可以用于任一映射构造:
If you're using an alternate to std::map
for the source associative container (such as std::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:
这对于作为翻转源的 std::map
和 std::unordered_map
都有效.
This will work for both std::map
and std::unordered_map
as the source of the flip.
这篇关于使用值对 std::map 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!