下面的代码将把数组中每种 colored颜色 的最大值转换为哈希图.也是在Rust Playground年.

use std::collections::HashMap;
use std::cmp;

fn main() {
    let array = [
        ("blue", 1),
        ("green", 2),
        ("red", 3),
        ("blue", 4),
        ("green", 1),
        ("red", 2),
    ];
    
    let mut scores = HashMap::new();
    
    // Convert array of key value into hashmap
    array
        .into_iter()
        .for_each(|(color, color_count)| {
            // Update the HashMap
            scores
                .entry(color)
                .and_modify(|e| { *e = cmp::max(*e, color_count) })
                .or_insert(color_count);
        });

    for (key, value) in &scores {
        println!("{}: {}", key, value);
    }
    
    println!("The product of the values: {}", scores.values().cloned().fold(1, |res, a| res * a));
}

它将得到以下结果:

blue: 4
green: 2
red: 3
The product of the values: 24

我面临的问题是,收集的array来自另一个map函数.但我面临的问题是,如果我将数组直接转换为HashMap,HashMap将存储最新的条目(数组的底部).我相信有一些更好的方法来链接整个事情,让它看起来更整洁?

推荐答案

作为一个小改变,我建议使用entry API,以避免第一次搜索.get(),第二次搜索.insert(),但这与您最初的try 没有太大区别.

    let mut scores = HashMap::<&str, usize>::new();
    for (color, color_count) in array {
        scores
            .entry(color)
            .and_modify(|c| *c = (*c).max(color_count))
            .or_insert(color_count);
    }

一种完全不同的计算产品的方法,不使用哈希图,将依赖于不稳定的.group_by()特性(然后用nightly编译).

#![feature(slice_group_by)]

fn main() {
    let mut array = [
        ("blue", 1),
        ("green", 2),
        ("red", 3),
        ("blue", 4),
        ("green", 1),
        ("red", 2),
    ];

    array.sort_unstable();
    let p = array
        .group_by(|a, b| a.0 == b.0)
        .map(|g| g.last().unwrap().1)
        .product::<usize>();
    println!("product: {:?}", p);
}
/*
product: 24
*/

不依赖不稳定的功能,我们可以使用itertools.

use itertools::Itertools;

fn main() {
    let mut array = [
        ("blue", 1),
        ("green", 2),
        ("red", 3),
        ("blue", 4),
        ("green", 1),
        ("red", 2),
    ];

    array.sort_unstable_by(|a, b| b.cmp(a));
    let p = array
        .into_iter()
        .dedup_by(|a, b| a.0 == b.0)
        .map(|e| e.1)
        .product::<usize>();
    println!("product: {:?}", p);
}
/*
product: 24
*/

我们可以回到(内部)哈希图...

use itertools::Itertools;

fn main() {
    let array = [
        ("blue", 1),
        ("green", 2),
        ("red", 3),
        ("blue", 4),
        ("green", 1),
        ("red", 2),
    ];

    let p = array
        .into_iter()
        .into_grouping_map()
        .max()
        .into_values()
        .product::<usize>();
    println!("product: {:?}", p);
}
/*
product: 24
*/

Rust相关问答推荐

为什么我需要在这个代码示例中使用&

将已知大小的切片合并成一个数组,

如果A == B,则将Rc A下推到Rc B

如何从铁 rust 中呼唤_mm_256_mul_ph?

为什么Rust函数的移植速度比C++慢2倍?

异步FN中的 rust 递归

如何格式化传入Rust中mysql crate的Pool::new的字符串

如何正确地将App handler传递给Tauri中的其他模块?

如何在递归数据 struct 中移动所有权时变异引用?

如何高效地将 struct 向量中的字段收集到单独的数组中

零拷贝按步骤引用一段字节

如果变量本身不是None,如何返回;如果没有,则返回None&Quot;?

为什么我需要 to_string 函数的参考?

将泛型中的 Box 转换为 rust 中的 Box

存储返回 impl Trait 作为特征对象的函数

OpenGL 如何同时渲染无纹理的四边形和有纹理的四边形

类型判断模式匹配panic

使用自定义 struct 收集 Vec

Rust 将特性传递给依赖项

为什么一个整型变量赋值给另一个变量后仍然可以使用?