如何将 HashMap 的值收集到向量中? [英] How do I collect the values of a HashMap into a vector?
问题描述
我在文档中找不到将 HashMap
的值收集到 Vec
的方法.我有 score_table: HashMap<Id, Score>
并且我想将所有 Score
放入 all_scores: Vec
p>
我很想使用 values
方法(all_scores = score_table.values()
),但它不起作用,因为 values 不是 Vec代码>.
我知道 Values
实现了 ExactSizeIterator
特征,但我不知道如何在不手动编写 for 循环和推送的情况下将迭代器的所有值收集到向量中向量中的值一个接一个.
我也尝试使用 std::iter::FromIterator;
但以类似以下内容结束:
all_scores = Vec::from_iter(score_table.values());
预期类型`std::vec::Vec<Score>`找到类型`std::vec::Vec<&Score>`
感谢 哈希映射宏拒绝类型检查,失败并显示误导性(并且看似错误)的错误消息?,我将其更改为:
all_scores = Vec::from_iter(score_table.values().cloned());
并且它不会对cargo check
产生错误.
这是一个好方法吗?
Iterator.collect
方法就是为这个特定的任务而设计的.你是对的,如果你想要一个实际值的向量而不是引用,你需要 .cloned()
(除非存储的类型实现 Copy
,如原语),所以代码如下所示:
all_scores = score_table.values().clone().collect();
在内部,collect()
只是使用 FromIterator
,但它也推断输出的类型.有时没有足够的信息来推断类型,因此您可能需要明确指定所需的类型,如下所示:
all_scores = score_table.values().cloned().collect::>();
I can not find a way to collect the values of a HashMap
into a Vec
in the documentation. I have score_table: HashMap<Id, Score>
and I want to get all the Score
s into all_scores: Vec<Score>
.
I was tempted to use the values
method (all_scores = score_table.values()
), but it does not work since values is not a Vec
.
I know that Values
implements the ExactSizeIterator
trait, but I do not know how to collect all values of an iterator into a vector without manually writing a for loop and pushing the values in the vector one after one.
I also tried to use std::iter::FromIterator;
but ended with something like:
all_scores = Vec::from_iter(score_table.values());
expected type `std::vec::Vec<Score>`
found type `std::vec::Vec<&Score>`
Thanks to Hash map macro refuses to type-check, failing with a misleading (and seemingly buggy) error message?, I changed it to:
all_scores = Vec::from_iter(score_table.values().cloned());
and it does not produce errors to cargo check
.
Is this a good way to do it?
The method Iterator.collect
is designed for this specific task. You're right in that you need .cloned()
if you want a vector of actual values instead of references (unless the stored type implements Copy
, like primitives), so the code looks like this:
all_scores = score_table.values().cloned().collect();
Internally, collect()
just uses FromIterator
, but it also infers the type of the output. Sometimes there isn't enough information to infer the type, so you may need to explicitly specify the type you want, like so:
all_scores = score_table.values().cloned().collect::<Vec<Score>>();
这篇关于如何将 HashMap 的值收集到向量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!