gpt4 book ai didi

hashmap - 使用 Rust HashMap - .find() 没有返回匹配的预期值

转载 作者:行者123 更新时间:2023-11-29 08:23:07 25 4
gpt4 key购买 nike

我想构建一个函数来计算元素在数组中出现的次数,但我无法解决编译时错误,这是我的代码

fn vec_count_elem(vec: Vec<int>) -> Vec<int> {
let mut counts: HashMap<int, int> = HashMap::new();;
let mut result: Vec<int>;

for el in vec.iter() {
match counts.find(el) {
Some(count) => {
let new_count: int = count + 1;
counts.remove(el);
counts.insert(*el, new_count)
},
None => counts.insert(*el, 0)
}
}
for value in counts.values() {
result.push(*value);
}

return result;
}

这是编译日志

/sorting/src/main.rs:40:9: 47:10 error: mismatched types: expected `()`, found `bool` (expected (), found bool)
/sorting/src/main.rs:40 match counts.find(el) {
/sorting/src/main.rs:41 Some(count) => {
/sorting/src/main.rs:42 let new_count: int = count + 1;
/sorting/src/main.rs:43 counts.remove(el);
/sorting/src/main.rs:44 counts.insert(*el, new_count)
/sorting/src/main.rs:45 },

看看这个例子 ( http://doc.rust-lang.org/std/collections/struct.HashMap.html#example ),counts.find(el) 应该为匹配运算符返回正确的数据类型

谢谢!

更新 1:第一个问题已解决(缺少 ;),谢谢 Arjan!现在我的问题在于我在 match 子句中访问计数 HashMap ,我收到此错误:

sorting/src/main.rs:50:21: 50:27 error: cannot borrow `counts` as mutable because it is also borrowed as immutable
sorting/src/main.rs:50 counts.remove(el);
^~~~~~
sorting/src/main.rs:46:20: 46:26 note: previous borrow of `counts` occurs here; the immutable borrow prevents subsequent moves or mutable borrows of `counts` until the borrow ends

有什么想法可以做到这一点吗?

最佳答案

使用 HashMap 的 .entry() 方法,您可以制作一个非常紧凑的版本:

use std::collections::hashmap::{HashMap, Occupied, Vacant};

fn vec_count_elem(vec: Vec<int>) -> Vec<int> {
let mut counts: HashMap<int, int> = HashMap::new();

for el in vec.iter() {
match counts.entry(*el) {
Occupied(mut e) => { *e.get_mut() += 1; },
Vacant(mut e) => { e.set(1); }
}
}

return counts.values().map(|i| *i).collect();
}

关于hashmap - 使用 Rust HashMap - .find() 没有返回匹配的预期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26546215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com