【问题标题】:Map "int Triplets" to int?将“int Triplets”映射到int?
【发布时间】:2012-04-06 14:13:52
【问题描述】:

使用 c++ std 的 unordered_map 我想将整数三元组映射到单个整数,我通常不使用哈希表(不知道它们很酷),但我不知道在这种情况下正确的方法,使用默认散列函数我应该直接映射三元组(类似于 ,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吗?
  • (“对”只是一种特殊的“元组”:有 2 个元素。)
  • 是的,我确实有权访问 std::tuple,我只是不习惯 C++ 库,我会检查一下

标签: c++ hash std unordered-map


【解决方案1】:

首先,您将使用std::tuple&lt;int, int, int&gt; 作为键类型。

接下来,您需要一种方法来散列一个元组,因为您可以散列每个元素。在 Boost 中有一个名为 hash_combine 的函数可以做到这一点,但由于我不清楚的原因,该函数未包含在标准中。不管怎样,就这样吧:

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

【讨论】:

    【解决方案2】:

    “最有效”似乎取决于您的编译器,但我会说 make_pair 解决方案看起来一团糟。更好地使用你自己的哈希函数......只要确保你组成一个像样的:)

    【讨论】:

      【解决方案3】:

      您使用一对配对的解决方案应该非常有效。就哈希而言,很难将三个整数映射到更简单的东西。

      【讨论】:

        猜你喜欢
        • 2015-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-15
        • 2012-02-16
        • 2016-02-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多