ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

c – 使用自定义散列函数插入unordered_set

2019-09-23 03:05:56  阅读:182  来源: 互联网

标签:unordered-set c c11


我有以下代码来制作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;

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

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

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

note: candidate is:
note: size_t Hash::operator()(const Interval&)
note:   candidate expects 1 argument, 2 provided  

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

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

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

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*’

解决方法:

第一个问题:

您正在传递字符串作为第二个模板参数,用于实例化unordered_set<>类模板. The second argument should be the type of your hasher functor,并且std :: string不是可调用对象.

或许打算写:

unordered_set<Interval, /* string */ Hash> test;
//                      ^^^^^^^^^^^^
//                      Why this?

另外,我建议使用开头和结尾以外的名称作为(成员)变量,因为这些是C标准库的算法名称.

第二个问题:

你应该记住,that the hasher function should be qualified as 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());
   }
};

第三个问题:

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

您目前没有为您的类Interval重载operator ==,因此您应该提供一个.例如:

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

结论:

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

标签:unordered-set,c,c11
来源: https://codeday.me/bug/20190923/1813483.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有