User defined hash in C++
1. cppreference 中的示例用法
Ref: http://en.cppreference.com/w/cpp/container/unordered_map/unordered_map
/*
Custom hash functions
*/
#include <unordered_map>
#include <vector>
#include <bitset>
#include <string>
#include <utility>
struct Key {
std::string first;
std::string second;
};
struct KeyHash {
std::size_t operator()(const Key& k) const
{
return std::hash<std::string>()(k.first) ^
(std::hash<std::string>()(k.second) << 1);
}
};
struct KeyEqual {
bool operator()(const Key& lhs, const Key& rhs) const
{
return lhs.first == rhs.first && lhs.second == rhs.second;
}
};
struct Foo {
Foo(int val_) : val(val_) {}
int val;
bool operator==(const Foo &rhs) const { return val == rhs.val; }
};
namespace std {
template<> struct hash<Foo> {
std::size_t operator()(const Foo &f) const {
return std::hash<int>{}(f.val);
}
};
}
int main()
{
// default constructor: empty map
std::unordered_map<std::string, std::string> m1;
// list constructor
std::unordered_map<int, std::string> m2 =
{
{1, "foo"},
{3, "bar"},
{2, "baz"},
};
// copy constructor
std::unordered_map<int, std::string> m3 = m2;
// move constructor
std::unordered_map<int, std::string> m4 = std::move(m2);
// range constructor
std::vector<std::pair<std::bitset<8>, int>> v = { {0x12, 1}, {0x01,-1} };
std::unordered_map<std::bitset<8>, double> m5(v.begin(), v.end());
//Option 1 for a constructor with a custom Key type
// Define the KeyHash and KeyEqual structs and use them in the template
std::unordered_map<Key, std::string, KeyHash, KeyEqual> m6 = {
{ {"John", "Doe"}, "example"},
{ {"Mary", "Sue"}, "another"}
};
//Option 2 for a constructor with a custom Key type
// Define a const == operator for the class/struct and specialize std::hash
// structure in the std namespace
std::unordered_map<Foo, std::string> m7 = {
{ Foo(1), "One"}, { 2, "Two"}, { 3, "Three"}
};
//Option 3: Use lambdas
// Note that the initial bucket count has to be passed to the constructor
struct Goo {int val; };
auto hash = [](const Goo &g){ return std::hash<int>{}(g.val); };
auto comp = [](const Goo &l, const Goo &r){ return l.val == r.val; };
std::unordered_map<Goo, double, decltype(hash), decltype(comp)> m8(10, hash, comp);
}
2. 基于Boost中的 hash_combine 函数写出如下适用性更强的代码
Ref: http://www.boost.org/doc/libs/1_35_0/doc/html/hash/combine.html
Ref: http://www.boost.org/doc/libs/1_35_0/doc/html/boost/hash_combine_id241013.html
Ref: The C++ Standard Library 2nd Edition
#pragma once
#include <functional>
// from boost (functional/hash):
// see http://www.boost.org/doc/libs/1_35_0/doc/html/hash/combine.html
template <typename T>
inline void hash_combine(std::size_t& seed, const T& val)
{
seed ^= std::hash<T>()(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
// auxiliary generic functions to create a hash value using a seed
template <typename T>
inline void hash_val(std::size_t& seed, const T& val)
{
hash_combine(seed, val);
}
template <typename T, typename... Types>
inline void hash_val(std::size_t& seed,
const T& val, const Types&... args)
{
hash_combine(seed, val);
hash_val(seed, args...);
}
// auxiliary generic function to create a hash value out of a heterogeneous list of arguments
template <typename... Types>
inline std::size_t hash_val(const Types&... args)
{
std::size_t seed = 0;
hash_val(seed, args...);
return seed;
}
上述辅助代码的使用如下:
Example of Providing Your Own Hash Function and Equivalence Criterion
#pragma once
#include <unordered_set>
#include <string>
#include <iostream>
#include "Utility.h"
#include "hashval.h"
using namespace std;
namespace HASHFUNC1_H
{
class Customer {
private:
string fname;
string lname;
long no;
public:
Customer(const string& fname_, const string& lname_, const long no_)
: fname(fname_), lname(lname_), no(no_)
{
}
friend ostream& operator << (ostream& strm, const Customer& c)
{
return strm << "[" << c.fname << "," << c.lname << ","
<< c.no << "]";
}
friend class CustomerHash;
friend class CustomerEqual;
//bool operator== (const Customer& c2) const
//{
// return no == c2.no;
//}
};
class CustomerHash {
public:
size_t operator() (const Customer& c) const
{
return hash_val(c.fname, c.lname, c.no);
}
};
class CustomerEqual {
public:
bool operator() (const Customer& c1, const Customer& c2) const
{
return c1.no == c2.no;
}
};
/*
As you can see, the equivalence function does not necessarily have to evaluate the same values as
the hash function. However, as written, it should be guaranteed that values that are equal according
the equivalence criterion yield the same hash value (which indirectly is the case here assuming that
customer numbers are unique).
*/
void f()
{
unordered_set<Customer, CustomerHash, CustomerEqual> custset;
custset.insert(Customer("nico", "josuttis", 42));
PRINT_ELEMENTS(custset);
cout << endl;
}
} // !HASHFUNC1_H
Using Lambdas as Hash Function and Equivalence Criterion
#pragma once
#include <unordered_set>
#include <string>
#include <iostream>
#include "hashval.h"
#include "Utility.h"
using namespace std;
namespace HASHFUNC2_H
{
class Customer {
private:
string fname;
string lname;
long no;
public:
Customer(const string& fn, const string& ln, long n)
: fname(fn), lname(ln), no(n)
{
}
string firstname() const
{
return fname;
}
string lastname() const
{
return lname;
}
long number() const
{
return no;
}
friend ostream& operator << (ostream& strm, const Customer& c)
{
return strm << "[" << c.fname << "," << c.lname << ","
<< c.no << "]";
}
};
/*
Note that you have to use decltype to yield the type of the lambda to be able to pass it as template
argument to the declaration of the unordered container. The reason is that for lambdas, no default
constructor and assignment operator are defined. Therefore, you also have to pass the lambdas to
the constructor. This is possible only as second and third arguments. Thus, you have to specify the
initial bucket size 10 in this case.
*/
void f()
{
// lambda for user-defined hash function
auto hash = [](const Customer& c)
{
return hash_val(c.firstname(), c.lastname(), c.number());
};
// lambda for user-defined equality criterion
auto eq = [](const Customer& c1, const Customer& c2)
{
return c1.number() == c2.number();
};
// create unordered set with user-defined behavior
unordered_set<Customer, decltype(hash), decltype(eq)> custset(10, hash, eq);
custset.insert(Customer("nico", "josuttis", 42));
PRINT_ELEMENTS(custset);
cout << endl;
}
} // !HASHFUNC2_H