给定两个相同长度的
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
转换为新向量?
只需复制您的值,例如通过取消引用
*
或在模式中使用 &
:
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
的值