私はのキーとして使用するカスタムOrderedTree
クラスを作成しています。std :: hashを実装するときの内部構造を変更します
私はツリーをハッシュするときカップルの事をしたい:
- (これは高価な操作であってもよいので)多分木のバランスをとる
- 、なまけハッシュを計算し、必要に応じてキャッシュします。
これらの操作のどちらも、オブジェクトの意味的同等性またはハッシュ値を変更しませんが、いくつかのプライベートフィールドを変更します。
OrderedTree
内のメンバーを変更しようとすると、std::hash<Tree>::operator()
は、unordered_set
が期待するconstの正しさに違反しているようです。
OrderedTree
をunordered_set
とすることはできますか?もしそうなら、どうですか?
編集:コメント欄にリクエストを1として
、概念の最小限の証拠:
#include <unordered_set>
std::size_t hash_combine(std::size_t a, std::size_t b) {
// TODO: Copy from boost source or something
return 0;
}
struct Node {
int value;
Node *left, *right, *parent;
std::size_t hash(std::size_t seed) const {
if (left != nullptr)
seed = left->hash(seed);
std::hash<int> hasher;
seed = hash_combine(seed, hasher(value));
if (right != nullptr)
seed = right->hash(seed);
return seed;
}
};
struct Tree {
Tree(): hash_(0), root(nullptr) {}
Node *root;
std::size_t hash() const {
if (hash_ == 0 && root != nullptr) {
hash_ = root->hash(7);
}
return hash_;
}
private:
std::size_t hash_;
};
namespace std {
template<>
struct hash<Tree> {
std::size_t operator()(const Tree& t) const {
return t.hash();
}
};
}
int main() {
std::unordered_set<Tree> set;
}
私がコンパイルしようとする私が取得:
Sample.cc:31:13: error: cannot assign to non-static data member within const member function 'hash'
hash_ = root->hash(7);
~~~~~^
Sample.cc:29:15: note: member function 'Tree::hash' is declared const here
std::size_t hash() const {
~~~~~~~~~~~~^~~~~~~~~~~~
「constの正しさに違反しているように見える」とはどういうことでしょうか?これはほんの一般的なものですか、それを実装する方法がわからないのですか、コンパイラのエラーが出ますか? –
「mutable」というキーワードを聞いたことがありますか? – JVApen
@JVApen私はかつてなかった。ありがとうございました!それはまさに私が探しているものと思われます。回答を投稿すると、私はそれを受け入れます。 – math4tots