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

use*_*561 22 c++ unordered-set c++11

我有以下代码来制作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 Hash::operator()(const Interval&)
note:   candidate expects 1 argument, 2 provided  
Run Code Online (Sandbox Code Playgroud)

我以为我只提供了一个论点......

我的插入代码有什么问题?


这是新的实例化代码:unordered_set<Interval, Hash> test; 但是,我仍然收到大量错误消息,例如:

note: candidate is:
note: size_t Hash::operator()(const Interval&) <near match>
note:   no known conversion for implicit ‘this’ parameter from ‘const Hash*’ to ‘Hash*’
Run Code Online (Sandbox Code Playgroud)

And*_*owl 36

第一个问题:

您将string作为unordered_set<>类模板实例化的第二个模板参数传递.第二个参数应该是您的hasher仿函数的类型,并且std::string不是可调用对象.

或许打算写:

unordered_set<Interval, /* string */ Hash> test;
//                      ^^^^^^^^^^^^
//                      Why this?
Run Code Online (Sandbox Code Playgroud)

此外,我建议使用除(beginend成员)变量以外的名称,因为这些是C++标准库的算法名称.

第二个问题:

你应该记住,hasher函数应该被限定为const,所以你的仿函数应该是:

struct Hash {
   size_t operator() (const Interval &interval) const {
   //                                           ^^^^^
   //                                           Don't forget this!
     string temp = to_string(interval.b) + 
                   to_string(interval.e) + 
                   to_string(interval.proteinIndex);
     return (temp.length());
   }
};
Run Code Online (Sandbox Code Playgroud)

第三个问题:

最后,如果您希望std::unordered_set能够使用类型的对象Interval,则需要定义与哈希函数一致的相等运算符.默认情况下,如果未指定任何类型参数作为std::unordered_set类模板的第三个参数,operator ==则将使用该参数 .

您目前没有operator ==为您的课程超载Interval,所以您应该提供一个.例如:

inline bool operator == (Interval const& lhs, Interval const& rhs)
{
    return (lhs.b == rhs.b) && 
           (lhs.e == rhs.e) && 
           (lhs.proteinIndex == rhs.proteinIndex); 
}
Run Code Online (Sandbox Code Playgroud)

结论:

完成上述所有修改后,您可以在此实例中看到您的代码编译.