首先,你會使用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;
}
};
}
您是否有權訪問[std :: tuple](http://en.cppreference.com/w/cpp/utility/tuple)? – 2012-03-22 01:15:05
(「對」只是一種特殊的「元組」,即2個元素)。 – 2012-03-22 01:16:19
是的,我確實需要訪問std :: tuple,我只是不習慣C++庫,我會檢查它 – Alb3rt 2012-03-22 01:19:58