Rust 在随机选择两个向量之间的元素时将迭代器收集到新向量

问题描述 投票:0回答:1

给定两个相同长度的

Vec<u8>
,尝试以给定的概率
p: f32
从每个索引中选择一个元素,如下,

fn select(xs: &Vec<u8>, ys: &Vec<u8>, p: f32) -> Vec<u8> {
    let mut rng = rand::thread_rng();
    xs
        .iter()
        .zip(ys.iter())
        .map(|(a, b)| if rng.gen_range(0.0..1.0) < p { a } else { b })
        .collect()
}

但是,

value of type `Vec<u8>` cannot be built from `std::iter::Iterator<Item=&u8>`

如何将迭代器

collect
转换为新向量?

rust iterator
1个回答
0
投票

只需复制您的值,例如通过取消引用

*
或在模式中使用
&

use rand::Rng;
fn shuffle(xs: &[u8], ys: &[u8], p: f32) -> Vec<u8> {
    let mut rng = rand::thread_rng();
    std::iter::zip(xs, ys)
        .map(|(x, &y)| if rng.gen_range(0.0..1.0) < p { *x } else { y })
        .collect()
}

显然,在您的代码中只需坚持其中一种方法,仅在此处显示两种可能性。

其他变化:

  • &Vec<u8>
    &[u8]
    因为它更通用,
  • xs.iter().zip(ys.iter())
    因为这真的不太可读,如果你多次压缩
    use std::iter
    iter::zip(xs, ys)
    ,否则直接使用该函数
  • 分别使用
    x
    y
    来表示
    xs
    ys
    的值
© www.soinside.com 2019 - 2024. All rights reserved.