我有一个向量a
,我需要复制此向量的一部分,比如a[n..n+3]
,k
次。
例如:
a = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
n = 2
k = 3
然后我想生成:
b = vec![2, 3, 4, 2, 3, 4, 2, 3, 4]
在之前的帮助下,我最终得到了以下内容:
a[n..n+3].iter().cloned().cycle().take(3 * k).collect()
这会是Rust-idiomatic吗?有更优选的方法吗?
答案 0 :(得分:1)
好的,所以看完Which is more idiomatic? Functional, imperative or a mix?之后 并在下面运行基准
#![feature(test)] extern crate test; use test::Bencher; #[bench] fn bench_target_func(b: &mut Bencher) { let a = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let n = 2; let k = 3; b.iter( || { let b: Vec = a[n..n+3].iter().cloned().cycle().take(3 * k).collect(); }); } #[bench] fn bench_target_imper(b: &mut Bencher) { let a = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let n = 2; let k = 3; b.iter( || { let mut b: Vec = Vec::with_capacity(k * 3); let mut it = a[n..n+3].iter().cloned().cycle(); for _ in 0..k*3 { b.push(it.next().unwrap()); } }); } #[bench] fn bench_target_imper2(b: &mut Bencher) { let a = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let n = 2; let k = 3; b.iter(|| { let mut b = Vec::with_capacity(3 * k); for _ in 0..k { b.extend_from_slice(&a[n..n + 3]); } }); } #[bench] fn bench_target_func2(b: &mut Bencher) { let a = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let n = 2; let k = 3; b.iter(|| { let b : Vec = (0..k).flat_map(|_| a[n..n+3].iter().cloned()).collect(); }); } fn main() { println!("Hello, world!"); }
我得到了以下结果:
test bench_target_func ... bench: 31 ns/iter (+/- 0) test bench_target_func2 ... bench: 97 ns/iter (+/- 1) test bench_target_imper ... bench: 37 ns/iter (+/- 0) test bench_target_imper2 ... bench: 29 ns/iter (+/- 0)
看来flat_map要慢得多。
答案 1 :(得分:0)
对我来说,你的例子似乎是Rust-idiomatic,但我会这样做:
let a = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let n = 2;
let k = 3;
let b : Vec<_> = (0..k).flat_map(|_| a[n..n+3].iter().cloned()).collect();
println!("{:?}", b);
我还提出了以下详细的方法,在某些情况下可能会有用。
let a = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let n = 2;
let k = 3;
let mut b = Vec::with_capacity(3 * k);
for _ in 0..k {
b.extend_from_slice(&a[n..n+3]);
}
println!("{:?}", b);