[英]Why does this HashMap key have to be dereferenced twice?
This function computes the mode of a Vec<i32>
using a HashMap
to keep count of the occurrence of each value.此 function 使用
HashMap
计算Vec<i32>
的模式,以记录每个值的出现次数。 I do not understand why this will not compile unless the key is deferenced twice in this last line:我不明白为什么除非在最后一行中两次引用密钥,否则这不会编译:
fn mode(vec: &Vec<i32>) -> i32 {
let mut counts = HashMap::new();
for n in vec {
let count = counts.entry(n).or_insert(0);
*count += 1;
}
**counts.iter().max_by_key(|a| a.1).unwrap().0
}
It has to be dereferenced twice because you've created a double reference.它必须被取消引用两次,因为您已经创建了双重引用。
&Vec<T>
which produces &T
.&Vec<T>
产生&T
的 &Vec<T> 。HashMap::iter
on HashMap<K, V>
which produces (&K, &V)
.(&K, &V)
的HashMap<K, V>
上调用HashMap::iter
。fn mode(vec: &[i32]) -> i32 {
let mut counts = std::collections::HashMap::new();
for &n in vec {
*counts.entry(n).or_insert(0) += 1;
}
counts.into_iter().max_by_key(|a| a.1).unwrap().0
}
See also:也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.