问题
I'm struggling to efficiently store information in pairs:
For instance I have two structs that represent (x,y) coords that i wish to calculate and store the distance between. Currently I am store all the values twice in a
unordered_map<pair<Struct1*,Struct2*,double>
My problem is that when searching I want the result <Struct1*,Struct2*> to turn up the same value as <Struct2*,Struct1*> that way I do not have to store information twice. I've thought about using a multimap but I think that std::hash<pair<pointer1,pointer2>> will hash to the same value as pair<pointer2,pointer1> any suggestions on how to do this?
Edit:
I've thought about doing a customer hash that simply adds the two hash values of the pointers using std::hash like:
size_t operator() (const pair<Location*,Location*> &key)
{
hash<Location*> hash1;
return (hash1(key.first) + hash1(key.second));
}
this works when I call find(struct1,struct2), however not when i call find(struct2,struct1)
回答1:
unordered_map does not only use the hash to identify a key, it also uses a comparison operator :
template<
class Key,
class T,
class Hash = std::hash<Key>,
class KeyEqual = std::equal_to<Key>,
class Allocator = std::allocator< std::pair<const Key, T> >
> class unordered_map;
It is the KeyEqual parameter which by default calls std::equal_to which by default calls operator==.
To do what you want, you can replace the KeyEqual parameter whith a custom one that when given a pair<struct1*, Struct2*> and a pair<struct2*, struct 1*> will return true independently of the order.
来源:https://stackoverflow.com/questions/20208498/unordered-multimap-of-pairs