HashSet作为其他HashSet的键

HashSet作为其他HashSet的键,hash,rust,hashset,Hash,Rust,Hashset,我试图使用一个HashSet作为其他HashSet的键。 我已经发现了为HashSet实现Hash特性的要点,但我无法使我的具体案例起作用 幸运的是,我的案例更受约束,因此我需要的是: 仅为类型HashSettrait实现HashSet 散列现在应该非常简单: 集合{“q3”、“q1”、“q2”}应该作为一个简单的有序连接字符串版本进行散列,类似于散列(“q1-q2-q3”)。获取“q1-q2-q3”不是问题,但是在散列中使用它会抛出我无法处理的所有类型的错误 这是我的实现尝试,但不起作用。

我试图使用一个
HashSet
作为其他
HashSet
的键。 我已经发现了为
HashSet
实现
Hash
特性的要点,但我无法使我的具体案例起作用

幸运的是,我的案例更受约束,因此我需要的是:

  • 仅为类型
    HashSet
    trait实现
    HashSet
  • 散列现在应该非常简单:
集合
{“q3”、“q1”、“q2”}
应该作为一个简单的有序连接字符串版本进行散列,类似于
散列(“q1-q2-q3”)
。获取
“q1-q2-q3”
不是问题,但是在
散列中使用它会抛出我无法处理的所有类型的错误

这是我的实现尝试,但不起作用。我认为
StateSet
包装器不是正确的方法,因为我丢失了所有重要的
HashSet
方法

use std::collections::{HashMap,HashSet};
use std::hash::{Hash,Hasher};

type State = String;
struct StateSet(HashSet<State>);

impl PartialEq for StateSet {
    fn eq(&self, other: &StateSet) -> bool {
        self.is_subset(&other) && other.is_subset(&self) 
    }
}

impl Eq for StateSet {}

impl Hash for StateSet {
    fn hash<H>(&self, state: &mut H) where H: Hasher {
        let a: Vec<State> = self.iter().collect();
        a.sort();
        for s in a.iter() {
            s.hash(state);
        }
    }

}

fn main() {
    let hmap: HashSet<StateSet> = HashSet::new(); 
}
使用std::collections::{HashMap,HashSet};
使用std::hash::{hash,Hasher};
类型状态=字符串;
结构状态集(HashSet);
状态集的impl PartialEq{
fn均衡器(自身、其他:&状态集)->bool{
self.is_子集(&other)和&other.is_子集(&self)
}
}
状态集{}的impl Eq
状态集的impl哈希{
fn散列(&self,state:&mut H),其中H:Hasher{
设a:Vec=self.iter().collect();
a、 排序();
国际热核聚变实验堆(iter)中的s{
s、 散列(状态);
}
}
}
fn main(){
让hmap:HashSet=HashSet::new();
}

()

您的代码有几个问题,主要是您试图通过在newtype包装器上调用方法来访问
HashSet
上的方法。您需要通过将
self
替换为
self.0
直接在
HashSet
上调用它们。以下是最终工作代码:

use std::collections::{HashMap,HashSet};
use std::hash::{Hash,Hasher};

type State = String;
struct StateSet(HashSet<State>);

impl PartialEq for StateSet {
    fn eq(&self, other: &StateSet) -> bool {
        self.0.is_subset(&other.0) && other.0.is_subset(&self.0) 
    }
}

impl Eq for StateSet {}

impl Hash for StateSet {
    fn hash<H>(&self, state: &mut H) where H: Hasher {
        let mut a: Vec<&State> = self.0.iter().collect();
        a.sort();
        for s in a.iter() {
            s.hash(state);
        }
    }

}

fn main() {
    let hmap: HashSet<StateSet> = HashSet::new(); 
}
使用std::collections::{HashMap,HashSet};
使用std::hash::{hash,Hasher};
类型状态=字符串;
结构状态集(HashSet);
状态集的impl PartialEq{
fn均衡器(自身、其他:&状态集)->bool{
self.0.is_子集(&other.0)和&other.0.is_子集(&self.0)
}
}
状态集{}的impl Eq
状态集的impl哈希{
fn散列(&self,state:&mut H),其中H:Hasher{
让mut a:Vec=self.0.iter().collect();
a、 排序();
国际热核聚变实验堆(iter)中的s{
s、 散列(状态);
}
}
}
fn main(){
让hmap:HashSet=HashSet::new();
}

另外,我强烈建议您使用here,它实现了
Hash
,因为它按排序顺序存储元素。它的
Hash
实现肯定比你的实现要快,你的实现对所有项目进行
O(n log(n))
排序。

次要细节:
Vec
对于a
中的s。非常感谢Dogbert!我将把你的答案标为正确答案。下面是一个使用您的代码的小示例,我将阅读更多关于BTreeSet的内容,看看它是否适合我的用例,非常感谢!道伯特:我已经测试了BTreeSet,它们正是我想要的。因为我处理的集合需要在我的代码的某些部分排序,所以它们自然适合。此外,我不需要实现使事情变得更简单的Hash特性。谢谢!