如何通过价值排序**的boost :: unordered_map **,并按此顺序仅返回键? [英] How to sort **boost::unordered_map** by value and return only keys in that order?
问题描述
如何排序的的boost :: unordered_map 按价值计算,该订单只返回键?
我已经像地图的boost :: unordered_map ,我需要,我需要在递增/递减INT值进行排序枚举ONY列表。
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
时,顾名思义,本身没有排序或排序就地。你可以插入值对成设置
(使用Boost.Range使这种东西更容易),它的价值排序,并得到从那里的钥匙。我用的是的std ::设为< 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屋!