如何通过价值排序**的boost :: unordered_map **,并按此顺序仅返回键? [英] How to sort **boost::unordered_map** by value and return only keys in that order?

查看:209
本文介绍了如何通过价值排序**的boost :: unordered_map **,并按此顺序仅返回键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何排序的的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆