将HashMap拆分为相等的块

时间:2015-06-24 13:54:09

标签: rust

HashMap分成相等的块的最佳方法是什么?例如,这是我分割Vec<String>

的方式
extern crate num_cpus;

fn main() {

    let cpu_count = num_cpus::get();

    let list: Vec<String> = vec!["one".into(), "two".into(), "three".into(), "four".into(), "five".into(), "six".into(), "seven".into(), "eight".into(), "nine".into(), "ten".into()];

    let chunk_len = (list.len() / cpu_count) as usize + 1;
    let mut chunks = Vec::new();
    for chunk in list.chunks(chunk_len) {
        chunks.push(chunk.to_owned());
    }

    for chunk in chunks {
        println!("{:?}", chunk);
    }

}

产生输出

["one", "two"]
["three", "four"]
["five", "six"]
["seven", "eight"]
["nine", "ten"]

我如何对HashMap<String, String>执行相同操作?

2 个答案:

答案 0 :(得分:4)

我不确定直接“ch”一个HashMap是否有意义。无论如何,解决方案显而易见:。你可以组建一个Vec(实际上是任何数组切片),所以只需使用它!毕竟,HashMap逻辑上只是(Key, Value)对的无序序列。

fn chunk_vec() {
    let cpu_count = 6 /*num_cpus::get()*/;

    let list: Vec<String> = [
        "one", "two", "three", "four", "five",
        "six", "seven", "eight", "nine", "ten"
    ].iter().map(|&s| s.into()).collect();

    let chunk_len = (list.len() / cpu_count) as usize + 1;
    let chunks: Vec<Vec<_>> = list.chunks(chunk_len)
        .map(|c| c.iter().collect())
        .collect();
    for chunk in chunks {
        println!("{:?}", chunk);
    }
}

fn chunk_hash() {
    use std::collections::HashMap;

    let cpu_count = 6 /*num_cpus::get()*/;

    let hash: HashMap<String, i32> = [
        ("one", 1), ("two", 2), ("three", 3), ("four", 4), ("five", 5),
        ("six", 6), ("seven", 7), ("eight", 8), ("nine", 9), ("ten", 10)
    ].iter().map(|&(k, v)| (k.into(), v)).collect();

    let list: Vec<_> = hash.into_iter().collect();

    let chunk_len = (list.len() / cpu_count) as usize + 1;
    let chunks: Vec<HashMap<_, _>> = list.chunks(chunk_len)
        .map(|c| c.iter().cloned().collect())
        .collect();
    for chunk in chunks {
        println!("{:?}", chunk);
    }
}

我冒昧地摆弄你的示例代码,以突出两个函数之间的相似性(和差异)。

答案 1 :(得分:3)

只要您不关心从HashMap中取出的元素的顺序,就可以通过调用{{1}将HashMap<String, String>转换为Vec<(String, String)> }

然后,您可以使用与转换your_map.into_iter().collect::<Vec<_>>()

相同的算法

为了能够与@ DK精确回答,我决定创建一个通用版本的分块算法:

Vec<String>

PlayPen

中试用