简体   繁体   English

std :: set的快速哈希 <int> 两个值?

[英]Fast hash for std::set<int> of two values?

I am using a std::set<int> for the key of a std map ( std::unordered_map<std::Set<int>,float> ). 我使用std::set<int>作为std map的键( std::unordered_map<std::Set<int>,float> )。 I need a hash for this set. 我需要这个集合的哈希。

The set will always be only two integers, whose values could be up to 2 million. 该集合将始终只有两个整数,其值可能高达200万。

Any ideas on a good and fast hash for such a key as performance is critical? 关于性能这样一个关键的良好和快速哈希的任何想法是至关重要的吗?

你可以使用boost :: hash_combine(): http//www.boost.org/doc/libs/1_44_0/doc/html/hash/combine.html

You didn't exactly state what the purpose of your lookup is, but maybe you should (or shouldn't): 您没有准确说明查找的目的是什么,但也许您应该(或不应该):

  • simply use a struct { int a, b; 只需使用struct {int a,b; } as a key - you control the insertion of the members (make sure a <= b ) }作为键 - 您控制成员的插入(确保a <= b

  • use a Sparse Matrix implementation 使用稀疏矩阵实现

Regards 问候

rbo RBO

I'd ditch the set idea (it is a waste of both memory and time to store two integers in a std::set ) and go with the pair. 我放弃了设定的想法(在std::set存储两个整数是浪费内存和时间)并且与它们一起使用。 Then define 然后定义

template <class A>
struct unordered_pair_hash
{
  std::size_t operator()(const std::pair<A, A>& p) const { 
    using std::min;
    using std::max;
    return std::hash<A>()(min(p.first, p.second))+
        17*std::hash<A>()(max(p.first, p.second));
  }
};

template <class A>
struct unordered_pair_eq
{
  bool operator()(const std::pair<A, A>& p1, const std::pair<A, A>& p2) const {
    using std::min;
    using std::max;
    return min(p1.first, p1.second)==min(p2.first, p2.second) &&
           max(p1.first, p1.second)==max(p2.first, p2.second);
  }
};

and then declare the map with a custom hash and equality. 然后使用自定义哈希和相等声明地图。

std::unordered_map<std::pair<int, int>, float, unordered_pair_hash<int>, unordered_pair_eq<int> > ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM