相关疑难解决方法(0)

如何在无序容器中为用户定义的类型专门化std :: hash <Key> :: operator()?

为了支持用户定义的键类型std::unordered_set<Key>std::unordered_map<Key, Value> 一个具有提供operator==(Key, Key)和散列函子:

struct X { int id; /* ... */ };
bool operator==(X a, X b) { return a.id == b.id; }

struct MyHash {
  size_t operator()(const X& x) const { return std::hash<int>()(x.id); }
};

std::unordered_set<X, MyHash> s;
Run Code Online (Sandbox Code Playgroud)

std::unordered_set<X> 使用类型的默认哈希来编写会更方便X,就像编译器和库中的类型一样.咨询后

似乎可以专门化std::hash<X>::operator():

namespace std { // argh!
  template <>
  inline size_t 
  hash<X>::operator()(const X& x) const { return …
Run Code Online (Sandbox Code Playgroud)

c++ hash unordered-map unordered-set c++11

95
推荐指数
2
解决办法
5万
查看次数

使用自定义哈希函数插入unordered_set

我有以下代码来制作unordered_set<Interval>.编译好了.

struct Interval {
  unsigned int begin;
  unsigned int end;
  bool updated;   //true if concat.  initially false
  int patternIndex;  //pattern index. valid for single pattern
  int proteinIndex;   //protein index.  for retrieving the pattern
};

struct Hash {
  size_t operator()(const Interval &interval);
};

size_t Hash::operator()(const Interval &interval){
  string temp = to_string(interval.begin) + to_string(interval.end) + to_string(interval.proteinIndex);
  return hash<string>()(temp);
}

unordered_set<Interval, string, Hash> test;
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用此代码插入时,我无法编译:

for(list<Interval>::iterator i = concat.begin(); i != concat.end(); ++i){
  test.insert((*i));
}
Run Code Online (Sandbox Code Playgroud)

而且,我无法确定错误消息的问题,例如:

note: candidate is:
note: size_t …
Run Code Online (Sandbox Code Playgroud)

c++ unordered-set c++11

22
推荐指数
1
解决办法
3万
查看次数

标签 统计

c++ ×2

c++11 ×2

unordered-set ×2

hash ×1

unordered-map ×1