是否可以覆盖 std::string 的 == 逻辑以进行散列?
Is it possible to overwrite == logic of std::string for hashing?
我想做的是使用素数为字谜创建散列;但是,由于 ==
运算符,必须创建一个额外的 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;
}
从 std::string 创建您自己的 class 并将您的重载运算符添加到新的 class
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;
因此您可以将自己的相等谓词替换为第四个模板参数。
我想做的是使用素数为字谜创建散列;但是,由于 ==
运算符,必须创建一个额外的 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;
}
从 std::string 创建您自己的 class 并将您的重载运算符添加到新的 class
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;
因此您可以将自己的相等谓词替换为第四个模板参数。