c++ - 如何按值对 **boost::unordered_map** 进行排序并按该顺序仅返回键?

标签 c++ boost

如何按值对 boost::unordered_map 进行排序并仅返回该顺序的键? 我有像 boost::unordered_map 这样的 map ,我需要在 asc/desc 中按 int 值排序的枚举列表。

最佳答案

unordered_map顾名思义,本质上是不可排序或可就地排序的。您可以将值对插入 set这是按值排序并从那里获取键(使用 Boost.Range 使这些东西更容易)。我用 std::set<T*>不支付复制配对对象的费用。

#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.

关于c++ - 如何按值对 **boost::unordered_map** 进行排序并按该顺序仅返回键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12263925/

相关文章:

c++ - 将二进制数写入文件时出现意外结果 [C++]

c++ - boost::asio::streambuf 为空?

c++ - 使用 while(inf.good) 读取整数文件

c++ - Boost.Spirit 重叠 Action /重用终端 token

c++ - 将 Boost multi_index 用于组合键

multithreading - Boost:可能从任何线程解锁互斥锁吗?

c++ - BOOST_FOREACH 对 boost::shared_ptr<list> 的迭代

c++ - boost::any 的用途?

c++ - 如何在 multi_index_container 中添加指定的有序唯一索引

c++ - 在 C++ 中使用 ofstream 将 32 位二进制数据写入文件