gpt4 book ai didi

vector - 如何将向量的一部分复制 k 次到另一个向量中?

转载 作者:行者123 更新时间:2023-11-29 08:29:43 25 4
gpt4 key购买 nike

我有一个向量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 惯用语吗?有没有更好的方法来做到这一点?

最佳答案

好吧,所以读完这个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 慢得多。

关于vector - 如何将向量的一部分复制 k 次到另一个向量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48015781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com