2012-03-22 106 views
2

使用C++ std的unordered_map我想將一個整數三元組映射到一個整數,我通常不使用散列表(不知道它們太酷了),但在這種情況下我不知道正確的方法,使用默認的散列函數應該i中的三元組直接映射(像< < INT,INT>,INT> - > INT)將「int triplets」映射爲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; 

這兩種方法的工作,但我想知道一個是最有效的。謝謝

+1

您是否有權訪問[std :: tuple](http://en.cppreference.com/w/cpp/utility/tuple)? – 2012-03-22 01:15:05

+0

(「對」只是一種特殊的「元組」,即2個元素)。 – 2012-03-22 01:16:19

+0

是的,我確實需要訪問std :: tuple,我只是不習慣C++庫,我會檢查它 – Alb3rt 2012-03-22 01:19:58

回答

3

首先,你會使用std::tuple<int, int, int>作爲關鍵類型。

接下來,您需要一種散列元組的方法,因爲您可以散列每個元素。在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; 
     } 
    }; 
} 
0

你的解決方案與一對配對應該是非常有效的。就散列而言,難以將三個整數映射到更簡單的地方。

1

「最高效」似乎取決於您的編譯器,但我會說make_pair解決方案看起來像一團糟。更好地使用你自己的散列函數...只要確保你是一個體面的:)