繁体   English   中英

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

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

我使用std::set<int>作为std map的键( std::unordered_map<std::Set<int>,float> )。 我需要这个集合的哈希。

该集合将始终只有两个整数,其值可能高达200万。

关于性能这样一个关键的良好和快速哈希的任何想法是至关重要的吗?

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

您没有准确说明查找的目的是什么,但也许您应该(或不应该):

  • 只需使用struct {int a,b; }作为键 - 您控制成员的插入(确保a <= b

  • 使用稀疏矩阵实现

问候

RBO

我放弃了设定的想法(在std::set存储两个整数是浪费内存和时间)并且与它们一起使用。 然后定义

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);
  }
};

然后使用自定义哈希和相等声明地图。

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