gpt4 book ai didi

c++ - 将 "int Triplets"映射到 int?

转载 作者:搜寻专家 更新时间:2023-10-31 01:15:41 25 4
gpt4 key购买 nike

使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com