如何按值对 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/