c++ - 是否可以覆盖 std::string 的 == 逻辑以进行散列?

标签 c++ hash unordered-map

我想做的是使用素数为 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;
}

最佳答案

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;

因此您可以将自己的相等谓词替换为第四个模板参数。

关于c++ - 是否可以覆盖 std::string 的 == 逻辑以进行散列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36564926/

相关文章:

c - 哈希码无效

android - 如何在 Windows 8 中生成 SHA1 和 key 哈希

Ruby:获取哈希中的所有键(包括子键)

c++ - 使用 boost 序列化、std::tr1::unordered_map 和自定义键的奇怪行为

c++ - 使用 unordered_map 表示对称稀疏矩阵的有效方法

c++ - 等效于 C++ iostream 的 StreamReader.ReadToEnd()

c++ - 当代码中不存在代码行时,如何解决 Visual Studio 2010 C++ 中的错误 C2719

c++ - 我可以创建字符串和 atomic<int> 键值对的 unordered_map 吗?

c++ - 构造函数模板

c++ - Visual Studio 图形调试器引发读取访问冲突异常