性病::地图,如何按值进行排序,然后按键性病、按键、地图

2023-09-11 00:00:35 作者:人潮拥挤有你足矣

我要排序的映射按值,然后按键。我有这样的内容的地图...

I need to sort a map by value, then by key. I have a map with contents like this...

  1  realistically
  8         really
  4         reason
  3     reasonable
  1     reasonably
  1     reassemble
  1    reassembled
  2      recognize
 92         record
 48        records
  7           recs

我需要按顺序值,但最厉害的是,关键需要按字母顺序排列后的值是为了。什么是去了解这一点的最好方法是什么?

I need to get the values in order, but the kicker is that the keys need to be in alphabetical order after the values are in order. What is the best way to go about this?

推荐答案

的std ::地图将其元素由键排序。它不关心时排序。

std::map will sort its elements by keys. It doesn't care about the values when sorting.

您可以使用的std ::矢量<的std ::对< K,V>> 然后进行排序它使用的std ::排序然后按的std :: stable_sort

You can use std::vector<std::pair<K,V>> then sort it using std::sort followed by std::stable_sort:

std::vector<std::pair<K,V>> items;

//fill items

//sort by value using std::sort
std::sort(items.begin(), items.end(), value_comparer);

//sort by key using std::stable_sort
std::stable_sort(items.begin(), items.end(), key_comparer);

第一次排序应该使用的std ::排序,因为它是 n日志(N),然后用的std :: stable_sort N(的log(n))^ 2 在最坏的情况下。

The first sort should use std::sort since it is nlog(n), and then use std::stable_sort which is n(log(n))^2 in the worst case.

请注意,虽然的std ::排序选择性能原因,的std :: stable_sort 是需要正确的订购,只要你想的顺序按值为preserved。

Note that while std::sort is chosen for performance reason, std::stable_sort is needed for correct ordering, as you want the order-by-value to be preserved.

在注释@gsf指出,你可以使用的只有的的std ::排序如果你选择一个比较器,其比较第一,如果他们是平等的,排序

@gsf noted in the comment, you could use only std::sort if you choose a comparer which compares values first, and IF they're equal, sort the keys.

auto cmp = [](std::pair<K,V> const & a, std::pair<K,V> const & b) 
{ 
     return a.second != b.second?  a.second < b.second : a.first < b.first;
};
std::sort(items.begin(), items.end(), cmp);

这应该是有效的。

别急,还有一个更好的方法:店的std ::对&LT; V,K&GT; 对&LT代替的std ::; K, V&GT; ,然后你根本不&mdash需要任何比较器;标准的比较器的的std ::对就足够了,因为它比较第一(即 V )的第一则第二 K

But wait, there is a better approach: store std::pair<V,K> instead of std::pair<K,V> and then you don't need any comparer at all — the standard comparer for std::pair would be enough, as it compares first (which is V) first then second which is K:

std::vector<std::pair<V,K>> items;
//...
std::sort(items.begin(), items.end());

这应该工作太棒了。