In C++, I often would like to created an unordered std::unordered_set
or std::unordered_map
of some type like std::tuple<int,int,int>
or std::pair<int,int>
. But I haven't found a way to do so that is fast. My custom hash functions are all slow. By slow I mean that programs that use them run faster if use the ordered version (set
or map
).
Here's an example of a custom hash function I created. I'm following examples I found on the internet. This type of example seems to be common. (An exclusive-or between primitive fields in a large data type).
using namespace std;
typedef pair<int,int> pi;
struct pair_hash
{
size_t operator()(const pi& p) const
{
auto h1 = hash<int>{}(p.first);
auto h2 = hash<int>{}(p.second);
return h1 ^ h2;
}
};
Here's another one:
using namespace std;
typedef tuple<int,int,int,int> t4;
struct t4_hash
{
size_t operator()(const t4 t) const
{
auto h1 = hash<int>{}(get<0>(t));
auto h2 = hash<int>{}(get<1>(t));
auto h3 = hash<int>{}(get<2>(t));
auto h4 = hash<int>{}(get<3>(t));
return h1 ^ h2 ^ h3 ^ h4;
}
};