如何排序** boost :: unordered_map **的值,并只返回键的顺序? [英] How to sort **boost::unordered_map** by value and return only keys in that order?
问题描述
如何按值对 boost :: unordered_map 进行排序,并仅按顺序返回键?
我有像 boost :: unordered_map 的地图,我需要我需要一个枚举列表,按照asc / desc中的int值排序。
How to sort boost::unordered_map by value and return only keys in that order ? I have map like boost::unordered_map and I need I need ony list of enums sorted by int values in asc/desc.
推荐答案
顾名思义, unordered_map
本质上不是就地排序或可排序。您可以将值对插入到一个 set
中,该值在值上排序并从那里获取键(使用Boost.Range使这个东西更容易)。我使用 std :: set< T *>
不支付复制对对象的成本。
An unordered_map
is, as the name implies, inherently not sorted or sortable in-place. You could insert the value pairs into a set
that is sorted on the value and get the keys from there (using Boost.Range to make this stuff easier). I use a std::set<T*>
to not pay the cost of copying the pair objects.
#include <iostream>
#include <set>
#include <unordered_map>
#include <boost/range/adaptor/map.hpp>
#include <boost/range/adaptor/indirected.hpp>
#include <boost/range/adaptor/transformed.hpp>
struct compare_second{
template<class Pair>
bool operator()(Pair* lhs, Pair* rhs) const{
return lhs->second < rhs->second;
}
};
template<class T>
struct make_pointer{
typedef T* result_type;
T* operator()(T& v) const{ return &v; }
};
int main(){
using namespace boost::adaptors;
std::unordered_map<int, int> m{{0,4},{1,3},{2,2},{3,1},{4,0}};
typedef std::unordered_map<int,int>::value_type pair_type;
auto p = m | transformed(make_pointer<pair_type>());
std::set<pair_type*, compare_second> value_ordered(p.begin(), p.end());
for(auto x : value_ordered | indirected | map_keys)
std::cout << x << " ";
}
这篇关于如何排序** boost :: unordered_map **的值,并只返回键的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!