使用unordered_set时,struct中嵌套结构的散列函数
Hashing function for nested struct in struct when using an unordered_set
我试图使用一个unordered_set来维护一个唯一的结构体列表。我已经为结构体Name定义了散列函数,但是当我扩展Name结构体以包含另一个结构体成员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);
}
};
您从未定义过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;
相关文章:
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 用C#中的并集模拟C++嵌套结构
- 如何在 C++11 中查找和更新向量中的一个嵌套结构
- Lambda 捕获、初始值设定项和嵌套结构
- 使用g++静态初始化带有命名标签的嵌套C++结构
- 重载嵌套结构/类的流插入运算符
- C++将结构传递给函数以访问嵌套结构
- C++ 在外部使用嵌套结构实现类函数
- 嵌套结构,从由空行分隔的文件中读取数据
- 在 glsl opengl 中将嵌套结构数组作为统一传递
- 受保护的嵌套结构不能用作派生外部类中的返回类型?
- C++中的嵌套结构
- 使用嵌套结构初始化并集
- C++ 中的嵌套结构函数
- C++中匿名类型的嵌套结构
- c++ 嵌套结构映射找不到成员
- C 嵌套结构上的 g++ 编译错误
- 不能使用嵌套结构中的联合元素作为 scanf() 的参数来存储所需的值
- 如何将值添加到嵌套结构中,该结构在C++中有两个指针