私がしようとしているのは、素数を使ってアナグラムのハッシュを作成することです。しかし、==
演算子のために余分なstruct key
を作成しなければならないのはやや不便です。 std :: stringの既存の==
をオーバーロードするための回避策がありますか?ハッシュのために==ロジック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;
}
継承を使用します。 – tomascapek
@RainbowTom:しないでください。 'std :: string'は基本クラスとしてではなく、値クラスとして設計されています。 C++ **は 'int'から継承するのを止め、' ** std :: string'を継承することを止めるべきです**。 – MSalters
@MSalters毎日スマートに、ありがとう! – tomascapek