使用unordered_set时,在结构中嵌套结构的哈希功能
-
25-10-2019 - |
题
我正在尝试使用unordered_set来维护唯一的结构列表。我已经定义了struct,name的哈希函数,但是当我将名称struct扩展到包含另一个struct成员的地址时,我会收到编译错误。我知道我需要指定必须如何进行地址结构,但是我似乎无法弄清楚在哪里/如何。
#include <unordered_set>
#include <string>
using namespace std;
struct Address
{
int num;
};
struct Name
{
string first;
string second;
Address address;
};
struct hashing_fn {
size_t operator()(const Address &a ) const
{
return hash<int>()(a.num);
}
size_t operator()(const Name &name ) const
{
return hash<string>()(name.first) ^ hash<string>()(name.second) ^ hash<Address>()(name.address);
}
};
int main(int argc, char* argv[])
{
unordered_set<Name,hashing_fn> ids;
return 0;
}
更新
只是为了完成,这就是解决方案:
template<>
struct hash<typename Address> {
size_t operator()(const Address &a ) const
{
return hash<int>()(a.num);
}
};
解决方案
您从未定义 hash<Address>
呢相反,您必须使用自己的功能 operator()(name.address)
.
简单的Xoring也许不是最好的解决方案。我强烈建议您复制Boost的 hash_combine()
, ,将整个负载放入 namespace std
:
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);
}
namespace std
{
template <> struct hash<Address>
{
inline size_t operator()(const Address & a) const
{
return hash<int>()(a.num);
}
};
template <> struct hash<Name>
{
inline size_t operator()(const Name & a) const
{
size_t seed = 0;
hash_combine(seed, name.first);
hash_combine(seed, name.second);
hash_combine(seed, name.address);
return seed;
}
};
}
现在,您可以直接使用类型(如果实现平等比较器): std::unordered_set<Name> s;
不隶属于 StackOverflow