无序 - 多对地图 [英] Unordered-MultiMap of Pairs
问题描述
我很难成对有效地存储信息:
例如,我有两个结构体表示(x,y)坐标,我希望计算和存储距离之间。目前我在一个
unordered_map< pair< struct1 *,Struct2 *,double>
我的问题是,在搜索时我想要结果< Struct1 *,Struct2 *>
与< Struct2 *,Struct1 *>
相同的值,那样我不必存储信息两次。我想过使用多图,但我认为 std :: hash< pair< pointer1,pointer2>>
将哈希与 pair< pointer2,pointer1>
有关如何执行此操作的任何建议?
编辑:
$ b b
我想过做一个客户散列,只是使用std :: hash来添加指针的两个散列值:
size_t operator()(const pair< Location *,Location *>& key)
{
hash< Location * hash1;
return(hash1(key.first)+ hash1(key.second));
}
当我调用find(struct1,struct2),但是不是当我调用find(struct2,struct1)
unordered_map不仅使用散列来标识密钥,还使用比较运算符:
模板<
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;
它是 KeyEqual
调用 std :: equal_to
其中默认调用 operator ==
。
要做你想要的,你可以替换 KeyEqual
参数,当给定一个对< struct1 *,Struct2 * < / c $ c>将返回
true
独立于订单。
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)
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.
这篇关于无序 - 多对地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!