我有一个键类型为 HashMap
(i64,usize)
假设我有一个用例,只使用键元组的第一部分从这个 HashMap 中检索数据。
例如我有这样的样本数据
(-1, 1): "1st -1 Resident",
(1, 1): "1st 1 Resident",
(1, 0): "Oth 1 Resident",
(1, 2): "2nd 1 Resident",
(-1, 2): "2nd -1 Resident",
(-1, 0): "Oth -1 Resident"
我想以
-1
作为键元组的第一个条目来检索或操作所有数据。或者就上面的例子而言,-1
的所有居民。
我目前正在这样做,遍历 Hashmap 中的所有条目并手动检查键元组的第一部分。
use std::collections::HashMap;
fn main(){
let mut hmap: HashMap<(i64,usize), &str> = HashMap::new();
hmap.insert((-1,0), "Oth -1 Resident");
hmap.insert((-1,1), "1st -1 Resident");
hmap.insert((-1,2), "2nd -1 Resident");
hmap.insert((1,0), "Oth 1 Resident");
hmap.insert((1,1), "1st 1 Resident");
hmap.insert((1,2), "2nd 1 Resident");
for (k,v) in &hmap {
if k.0 == -1 {
println!("{:?}",v);
}
}
}
有没有更好的方法来做到这一点? 这是我当前工作的链接(游乐场链接)
有没有更好的方法来做到这一点?
不使用散列映射,因为条目是通过 entire 键的散列本地化的,因此不可能进行部分匹配。
BTreeMap
:BTreeMap 的条目基于键的ordering 定位,因此您可以基于范围迭代子集 也就是进行前缀或范围匹配(即这就是为什么例如数据库索引默认使用 btrees,它提供比散列更灵活的查询)。
在这里你可以请求从
(-1, usize::MIN)
开始到(0, usize::MIN)
结束的范围,它会给你所有以-1
开头的条目。
use std::collections::BTreeMap;
fn main(){
let mut hmap: BTreeMap<(i64,usize), &str> = BTreeMap::new();
hmap.insert((-1,0), "Oth -1 Resident");
hmap.insert((-1,1), "1st -1 Resident");
hmap.insert((-1,2), "2nd -1 Resident");
hmap.insert((1,0), "Oth 1 Resident");
hmap.insert((1,1), "1st 1 Resident");
hmap.insert((1,2), "2nd 1 Resident");
for (k,v) in hmap.range((-1, usize::MIN)..(0, usize::MIN)) {
println!("{k:?} {v}");
}
}
输出:
(-1, 0) Oth -1 Resident
(-1, 1) 1st -1 Resident
(-1, 2) 2nd -1 Resident