我需要排序一个std::map
按值,然后按键。该地图包含如下数据:
1 realistically
8 really
4 reason
3 reasonable
1 reasonably
1 reassemble
1 reassembled
2 recognize
92 record
48 records
7 recs
我需要按顺序获取值,但更重要的是,在值按顺序排列后,键需要按字母顺序排列。我怎样才能做到这一点?
std::map
将对其元素进行排序keys
。它不关心values
排序时。
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::sort
因为它是nlog(n)
,然后使用std::stable_sort
这是n(log(n))^2
在最坏的情况下。
请注意,虽然std::sort
出于性能原因而选择,std::stable_sort
正确排序需要,因为您希望保留按值排序。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)