How to sort **boost::unordered_map** by value and

2019-05-31 20:27发布

问题:

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.

回答1:

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 << " ";
}

Live example.



回答2:

You can use Boost Multi-Index Library. boost::multi_index_container can have ordered state and unordered state.



回答3:

The simplest method is to copy the values into a vector and sort them by the mapped type:

std::vector<value_type> values(std::begin(map), std::end(map));
boost::sort(boost::make_range(values),
    [](const value_type &x, const value_type &y) { return x.second < y.second; });
std::vector<key_type> keys;
boost::push_back(keys, boost::make_range(values) | boost::map_keys));


标签: c++ boost