【问题标题】:How to insert struct into vector that lives inside the HashMap? [duplicate]如何将结构插入到位于 HashMap 内的向量中? [复制]
【发布时间】:2020-03-27 07:49:44
【问题描述】:

我的结构看起来像:

pub struct MonthlyProjection {
    pub sequence: u32,
    pub total_deposit: f64,
}

我有这个函数引用包含这些结构的向量:

fn generate_projections(simulation_results: &Vec<MonthlySimulationResult>)

在这个函数中,我必须将MonthlyProject 结构按它们的序列分组,并用它做一些计算。

所以这是我的逻辑:

  1. 创建可变HashMap&lt;u32, Vec&lt;MonthlySimulationResult&gt;&gt;,称为result_map
  2. simulation_results 向量上的 For 循环
  3. 如果result_map 已经具有给定序列号的向量,则将该项目插入该现有向量,然后更新result_map
  4. 如果result_map 没有给定序列号的现有向量,则创建新向量,插入结构,并更新result_map

你会怎么做?

【问题讨论】:

标签: rust


【解决方案1】:

如果你不介意引入额外的依赖,不妨看看 itertools:

https://docs.rs/itertools/0.9.0/itertools/trait.Itertools.html#method.group_by

否则,您可以使用entry API 编写一个 for 循环:

let mut result_map: HashMap<u32, Vec<_>> = HashMap::new();
for projection in simulation_results {
    result_map.entry(projection.sequence).or_default().push(projection);
}
result_map

(Playground.)

请注意,您指定了 MonthlyProjection 类型,但随后您使用 MonthlySimulationResult 指定了函数头及其返回类型,因此不清楚那里发生了什么。此外,您传递了对 Vec&lt;MonthlyProjection&gt; 的引用,但返回了一个可传递拥有的 MonthlySimulationResult,因此您需要在那里做一些事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-21
    • 2019-09-20
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 2016-12-06
    • 1970-01-01
    相关资源
    最近更新 更多