I'm trying to use an unordered_set to maintain an unique list of structs. I've defined the hash function for the struct, Name, however I receive compile errors when I extend the Name struct to contain another struct member, Address. I know I need to specify how the Address struct must be hashed, but I can't seem to figure out where/how.
#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;
}
Update
Just for completion, this was the fix:
template<>
struct hash<typename Address> {
size_t operator()(const Address &a ) const
{
return hash<int>()(a.num);
}
};