我正在尝试使用 unordered_set 来维护唯一的结构列表。我已经为结构 Name 定义了哈希函数,但是当我扩展 Name 结构以包含另一个结构成员 Address 时收到编译错误。我知道我需要指定必须如何对 Address 结构进行散列,但我似乎无法弄清楚在哪里/如何。
#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);
}
};