是否有可能覆盖std :: string的==逻辑进行散列?

Cha*_*han 1 c++ hash unordered-map

我要做的是使用prime为anagram创建哈希值; 但是struct key由于==操作员的缘故,不得不创建一个额外的东西.有没有解决方法来重载==std :: string 的现有?

#include <string>
#include <unordered_map>
#include <cstddef>
#include <iostream>


using namespace std;

int F[26] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29,  
             31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
             73, 79, 83, 89, 97, 101}; 

size_t f(const string &s) {
  size_t r = 1;
  for (auto c : s) {
    r *= F[c - 'a'] % 9999997;
  }
  return r;
}

// this struct seemed redundant!
struct key {
  const string s;

  key(const string s)
    :s(s) {}

  bool operator ==(const key &k) const {
    return f(s) == f(k.s);
  }
};

struct hasher {
  size_t operator()(const key &k) const {
    return f(k.s); 
  }
};

int main() {
  unordered_map<key, int, hasher> cnt;
  cnt[key{"ab"}]++;
  cnt[key{"ba"}]++;
  cout << cnt[key{"ab"}] << endl;
}
Run Code Online (Sandbox Code Playgroud)

bip*_*pll 7

unordered_map 被宣布为

template<
    class Key,
    class T,
    class Hash = std::hash<Key>,
    class KeyEqual = std::equal_to<Key>,
    class Allocator = std::allocator<std::pair<const Key, T>>
> class unordered_map;
Run Code Online (Sandbox Code Playgroud)

所以你可以用自己的等式谓词替换第四个模板参数.