Struct std::collections::HashSet 1.0.0[−][src]
pub struct HashSet<T, S = RandomState> { /* fields omitted */ }
Expand description
hash set,实现为 HashMap
,其中值为 ()
。
与 HashMap
类型一样,HashSet
要求元素实现 Eq
和 Hash
traits。这通常可以通过使用 #[derive(PartialEq, Eq, Hash)]
来实现。
如果您自己实现这些,那么拥有以下属性非常重要:
k1 == k2 -> hash(k1) == hash(k2)
换句话说,如果两个键相等,则它们的哈希值必须相等。
以某种方式修改项目的逻辑错误是由该项目的哈希值 (由 Hash
trait 确定) 或其相等性 (由 Eq
trait 确定) 在其位于集合中时发生变化的。
通常只有通过 Cell
,RefCell
,二进制状态,I/O 或不安全代码才能实现此操作。
没有指定由此类逻辑错误导致的行为 (可能包括 panics、不正确的结果、中止、内存泄漏或未终止),但不会是未定义的行为。
Examples
use std::collections::HashSet;
// 通过类型推断,我们可以省略显式类型签名 (在本示例中为 `HashSet<String>`)。
let mut books = HashSet::new();
// 添加一些书。
books.insert("A Dance With Dragons".to_string());
books.insert("To Kill a Mockingbird".to_string());
books.insert("The Odyssey".to_string());
books.insert("The Great Gatsby".to_string());
// 检查一个特定的。
if !books.contains("The Winds of Winter") {
println!("We have {} books, but The Winds of Winter ain't one.",
books.len());
}
// 删除一本书。
books.remove("The Odyssey");
// 遍历所有内容。
for book in &books {
println!("{}", book);
}
Run将 HashSet
与自定义类型一起使用的最简单方法是派生 Eq
和 Hash
。我们还必须导出 PartialEq
,这将在 Eq
中隐含在 future 中。
use std::collections::HashSet;
#[derive(Hash, Eq, PartialEq, Debug)]
struct Viking {
name: String,
power: usize,
}
let mut vikings = HashSet::new();
vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
vikings.insert(Viking { name: "Olaf".to_string(), power: 4 });
vikings.insert(Viking { name: "Harald".to_string(), power: 8 });
// 使用派生的实现来打印 Viking。
for x in &vikings {
println!("{:?}", x);
}
Run可以从数组初始化具有已知项列表的 HashSet
:
use std::collections::HashSet;
let viking_names = HashSet::from(["Einar", "Olaf", "Harald"]);
RunImplementations
pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, T, F>ⓘNotable traits for DrainFilter<'_, K, F>impl<K, F> Iterator for DrainFilter<'_, K, F> where
F: FnMut(&K) -> bool, type Item = K;
where
F: FnMut(&T) -> bool,
pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, T, F>ⓘNotable traits for DrainFilter<'_, K, F>impl<K, F> Iterator for DrainFilter<'_, K, F> where
F: FnMut(&K) -> bool, type Item = K;
where
F: FnMut(&T) -> bool,
impl<K, F> Iterator for DrainFilter<'_, K, F> where
F: FnMut(&K) -> bool, type Item = K;
创建一个迭代器,该迭代器使用闭包确定是否应删除值。
如果闭包返回 true,则该值将被删除并产生。 如果闭包返回 false,则该值将保留在列表中,并且不会由迭代器产生。
如果迭代器仅被部分消耗或根本没有消耗,则其余所有值仍将受到闭包的处理,如果返回 true,则将其删除并丢弃。
如果在闭包中出现 panic,或者在丢弃值时出现 panic,或者 DrainFilter
本身被泄漏,那么还有多少值将被关闭,这是未指定的。
Examples
将一个集合分为偶数和奇数值,重新使用原始集合:
#![feature(hash_drain_filter)]
use std::collections::HashSet;
let mut set: HashSet<i32> = (0..8).collect();
let drained: HashSet<i32> = set.drain_filter(|v| v % 2 == 0).collect();
let mut evens = drained.into_iter().collect::<Vec<_>>();
let mut odds = set.into_iter().collect::<Vec<_>>();
evens.sort();
odds.sort();
assert_eq!(evens, vec![0, 2, 4, 6]);
assert_eq!(odds, vec![1, 3, 5, 7]);
Run创建一个新的空哈希集,它将使用给定的哈希值来哈希键。
还使用默认的初始容量创建哈希集。
警告: hasher
通常是随机生成的,旨在允许 HashSet 抵抗导致许多冲突和非常差的性能的攻击。
使用此函数手动设置它可能会导致 DoS 攻击 vector。
传递的 hash_builder
应该为 HashMap 实现 BuildHasher
trait 才有用,有关详细信息,请参见其文档。
Examples
use std::collections::HashSet;
use std::collections::hash_map::RandomState;
let s = RandomState::new();
let mut set = HashSet::with_hasher(s);
set.insert(2);
Run创建一个具有指定容量的空 HashSet
,使用 hasher
对键进行哈希处理。
哈希集将能够至少保留 capacity
个元素而无需重新分配。如果 capacity
为 0,则不会分配哈希集。
警告: hasher
通常是随机生成的,旨在允许 HashSet 抵抗导致许多冲突和非常差的性能的攻击。
使用此函数手动设置它可能会导致 DoS 攻击 vector。
传递的 hash_builder
应该为 HashMap 实现 BuildHasher
trait 才有用,有关详细信息,请参见其文档。
Examples
use std::collections::HashSet;
use std::collections::hash_map::RandomState;
let s = RandomState::new();
let mut set = HashSet::with_capacity_and_hasher(10, s);
set.insert(1);
Run将集合的容量降低一个下限。 它将降低不低于提供的限制,同时保持内部规则,并可能根据调整大小策略留下一些空间。
如果当前容量小于下限,则为无操作。
Examples
use std::collections::HashSet;
let mut set = HashSet::with_capacity(100);
set.insert(1);
set.insert(2);
assert!(set.capacity() >= 100);
set.shrink_to(10);
assert!(set.capacity() >= 10);
set.shrink_to(0);
assert!(set.capacity() >= 2);
Runpub fn difference<'a>(
&'a self,
other: &'a HashSet<T, S>
) -> Difference<'a, T, S>ⓘNotable traits for Difference<'a, T, S>impl<'a, T, S> Iterator for Difference<'a, T, S> where
T: Eq + Hash,
S: BuildHasher, type Item = &'a T;
pub fn difference<'a>(
&'a self,
other: &'a HashSet<T, S>
) -> Difference<'a, T, S>ⓘNotable traits for Difference<'a, T, S>impl<'a, T, S> Iterator for Difference<'a, T, S> where
T: Eq + Hash,
S: BuildHasher, type Item = &'a T;
impl<'a, T, S> Iterator for Difference<'a, T, S> where
T: Eq + Hash,
S: BuildHasher, type Item = &'a T;
访问表示差异的值,即,在 self
中但不在 other
中的值。
Examples
use std::collections::HashSet;
let a = HashSet::from([1, 2, 3]);
let b = HashSet::from([4, 2, 3, 4]);
// 可以看作是 `a - b`。
for x in a.difference(&b) {
println!("{}", x); // 打印 1
}
let diff: HashSet<_> = a.difference(&b).collect();
assert_eq!(diff, [1].iter().collect());
// 请注意,差异不是对称的,并且 `b - a` 表示其他含义:
let diff: HashSet<_> = b.difference(&a).collect();
assert_eq!(diff, [4].iter().collect());
Runpub fn symmetric_difference<'a>(
&'a self,
other: &'a HashSet<T, S>
) -> SymmetricDifference<'a, T, S>ⓘNotable traits for SymmetricDifference<'a, T, S>impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S> where
T: Eq + Hash,
S: BuildHasher, type Item = &'a T;
pub fn symmetric_difference<'a>(
&'a self,
other: &'a HashSet<T, S>
) -> SymmetricDifference<'a, T, S>ⓘNotable traits for SymmetricDifference<'a, T, S>impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S> where
T: Eq + Hash,
S: BuildHasher, type Item = &'a T;
impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S> where
T: Eq + Hash,
S: BuildHasher, type Item = &'a T;
访问代表对称差异的值,即 self
或 other
中的值,但不能同时存在于两者中。
Examples
use std::collections::HashSet;
let a = HashSet::from([1, 2, 3]);
let b = HashSet::from([4, 2, 3, 4]);
// 以任意顺序打印 1、4。
for x in a.symmetric_difference(&b) {
println!("{}", x);
}
let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
assert_eq!(diff1, diff2);
assert_eq!(diff1, [1, 4].iter().collect());
Runpub fn intersection<'a>(
&'a self,
other: &'a HashSet<T, S>
) -> Intersection<'a, T, S>ⓘNotable traits for Intersection<'a, T, S>impl<'a, T, S> Iterator for Intersection<'a, T, S> where
T: Eq + Hash,
S: BuildHasher, type Item = &'a T;
pub fn intersection<'a>(
&'a self,
other: &'a HashSet<T, S>
) -> Intersection<'a, T, S>ⓘNotable traits for Intersection<'a, T, S>impl<'a, T, S> Iterator for Intersection<'a, T, S> where
T: Eq + Hash,
S: BuildHasher, type Item = &'a T;
impl<'a, T, S> Iterator for Intersection<'a, T, S> where
T: Eq + Hash,
S: BuildHasher, type Item = &'a T;
访问表示相交的值,即 self
和 other
中的值。
Examples
use std::collections::HashSet;
let a = HashSet::from([1, 2, 3]);
let b = HashSet::from([4, 2, 3, 4]);
// 以任意顺序打印 2,3。
for x in a.intersection(&b) {
println!("{}", x);
}
let intersection: HashSet<_> = a.intersection(&b).collect();
assert_eq!(intersection, [2, 3].iter().collect());
Run访问表示并集的值,即 self
或 other
中的所有值,没有重复项。
Examples
use std::collections::HashSet;
let a = HashSet::from([1, 2, 3]);
let b = HashSet::from([4, 2, 3, 4]);
// 以任意顺序打印 1、2、3、4。
for x in a.union(&b) {
println!("{}", x);
}
let union: HashSet<_> = a.union(&b).collect();
assert_eq!(union, [1, 2, 3, 4].iter().collect());
Runpub fn get_or_insert_owned<Q: ?Sized>(&mut self, value: &Q) -> &T where
T: Borrow<Q>,
Q: Hash + Eq + ToOwned<Owned = T>,
pub fn get_or_insert_owned<Q: ?Sized>(&mut self, value: &Q) -> &T where
T: Borrow<Q>,
Q: Hash + Eq + ToOwned<Owned = T>,
如果不存在给定的 value
,则将其拥有的副本插入到集合中,然后对集合中的值返回引用。
Examples
#![feature(hash_set_entry)]
use std::collections::HashSet;
let mut set: HashSet<String> = ["cat", "dog", "horse"]
.iter().map(|&pet| pet.to_owned()).collect();
assert_eq!(set.len(), 3);
for &pet in &["cat", "dog", "fish"] {
let value = set.get_or_insert_owned(pet);
assert_eq!(value, pet);
}
assert_eq!(set.len(), 4); // 插入了新的 "fish"
Runpub fn get_or_insert_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &T where
T: Borrow<Q>,
Q: Hash + Eq,
F: FnOnce(&Q) -> T,
pub fn get_or_insert_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &T where
T: Borrow<Q>,
Q: Hash + Eq,
F: FnOnce(&Q) -> T,
如果不存在给定的 value
,则将从 f
计算得出的值插入到集合中,然后对集合中的值返回引用。
Examples
#![feature(hash_set_entry)]
use std::collections::HashSet;
let mut set: HashSet<String> = ["cat", "dog", "horse"]
.iter().map(|&pet| pet.to_owned()).collect();
assert_eq!(set.len(), 3);
for &pet in &["cat", "dog", "fish"] {
let value = set.get_or_insert_with(pet, str::to_owned);
assert_eq!(value, pet);
}
assert_eq!(set.len(), 4); // 插入了新的 "fish"
Run如果集合是另一个集合的子集,则返回 true
,即 other
至少包含 self
中的所有值。
Examples
use std::collections::HashSet;
let sup = HashSet::from([1, 2, 3]);
let mut set = HashSet::new();
assert_eq!(set.is_subset(&sup), true);
set.insert(2);
assert_eq!(set.is_subset(&sup), true);
set.insert(4);
assert_eq!(set.is_subset(&sup), false);
Run如果集合是另一个集合的超集,则返回 true
,即 self
至少包含 other
中的所有值。
Examples
use std::collections::HashSet;
let sub = HashSet::from([1, 2]);
let mut set = HashSet::new();
assert_eq!(set.is_superset(&sub), false);
set.insert(0);
set.insert(1);
assert_eq!(set.is_superset(&sub), false);
set.insert(2);
assert_eq!(set.is_superset(&sub), true);
RunTrait Implementations
返回 self
和 rhs
的并集作为新的 HashSet<T, S>
。
Examples
use std::collections::HashSet;
let a = HashSet::from([1, 2, 3]);
let b = HashSet::from([3, 4, 5]);
let set = &a | &b;
let mut i = 0;
let expected = [1, 2, 3, 4, 5];
for x in &set {
assert!(expected.contains(x));
i += 1;
}
assert_eq!(i, expected.len());
Run从迭代器创建一个值。 Read more
创建一个消耗迭代器,即将每个值以任意顺序移出集合的迭代器。 调用此设置后将无法使用该设置。
Examples
use std::collections::HashSet;
let mut set = HashSet::new();
set.insert("a".to_string());
set.insert("b".to_string());
// 不能与常规 `.iter()` 一起收集到 Vec<String>。
let v: Vec<String> = set.into_iter().collect();
// 将以任意顺序打印。
for x in &v {
println!("{}", x);
}
Runtype Item = T
type Item = T
被迭代的元素的类型。