使用 c++ std 的 unordered_map 我想将整数三元组映射到单个整数,我通常不使用哈希表(不知道它们这么酷),但我不知道在这种情况下正确的方法,使用默认的哈希函数我应该直接映射三元组(类似于 << int,int >,int >->int)
std::unordered_map <std::make_pair <make_pair <int,int>,int>,int> hash;
或者可以使用函数将三元组映射到单个值,然后将该值与默认函数一起使用?
int mapping(int a, int b, int c){
}
std::unordered_map <int,int> hash;
两种方法都有效,但我想知道哪一种是最有效的。谢谢
最佳答案
首先,您可以使用 std::tuple<int, int, int>
作为 key 类型。
接下来,您需要一种对元组进行散列的方法,因为您可以对每个元素进行散列。有一个函数叫hash_combine
在 Boost 中可以做到这一点,但由于我不清楚的原因,该标准并未包含在内。无论如何,事情就是这样:
#include <tuple>
#include <utility>
template <class T>
inline void hash_combine(std::size_t & seed, const T & v)
{
std::hash<T> hasher;
seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
template <class Tuple, std::size_t Index = std::tuple_size<Tuple>::value - 1>
struct tuple_hash_impl
{
static inline void apply(std::size_t & seed, Tuple const & tuple)
{
tuple_hash_impl<Tuple, Index - 1>::apply(seed, tuple);
hash_combine(seed, std::get<Index>(tuple));
}
};
template <class Tuple>
struct tuple_hash_impl<Tuple, 0>
{
static inline void apply(std::size_t & seed, Tuple const & tuple)
{
hash_combine(seed, std::get<0>(tuple));
}
};
namespace std
{
template<typename S, typename T> struct hash<pair<S, T>>
{
inline size_t operator()(const pair<S, T> & v) const
{
size_t seed = 0;
::hash_combine(seed, v.first);
::hash_combine(seed, v.second);
return seed;
}
};
template<typename ...Args> struct hash<tuple<Args...>>
{
inline size_t operator()(const tuple<Args...> & v) const
{
size_t seed = 0;
tuple_hash_impl<tuple<Args...>>::apply(seed, v);
return seed;
}
};
}
关于c++ - 将 "int Triplets"映射到 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9815142/