是否可以连接迭代器?

问题描述 投票:1回答:1
let vec = iter::repeat("don't satisfy condition 1") // iterator such as next() always "don't " satisfy condition 1"
    .take_while(|_| {
        satisfycondition1.satisfy() // true is condition 1 is satisfied else false
    })
    .collect();

此代码创建n元素的向量,其中n等于条件1未被遵守的次数。

我现在要创建一个n + m元素的向量,其中n等于条件1不被遵守的次数,m是条件2未被遵守的次数。

代码应该像这样:

let vec = iter::repeat("dont't satisfy condition 1")
    .take_while(|_| {
        satisfycondition1.satisfy() 
    })
    .union(
        iter::repeat("has satisfed condition 1 but not 2 yet")
        .take_while(|_| {
            satisfycondition2.satisfy() 
        })
    )
    .collect();

我知道我可以创建两个向量然后连接它们但效率较低。

您可以使用此代码来了解重复内容:

use  std::iter;

fn main() {
    let mut c = 0;
    let z: Vec<_> = iter::repeat("dont't satisfy condition 1")
        .take_while(|_| {
            c = c + 1;
            let rep = if c < 5 { true } else { false };
            rep
        })
        .collect();
    println!("------{:?}", z);
}
rust iterator
1个回答
5
投票

好像std::iter::chain就是你要找的东西。

use std::iter;

fn main() {
    let mut c = 0;
    let mut d = 5;
    let z: Vec<_> = iter::repeat("don't satisfy condition 1")
        .take_while(|_| {
            c = c + 1;
            let rep = if c < 5 { true } else { false };
            rep
            // this block can be simplified to
            // c += 1;
            // c < 5
            // Clippy warns about this
        })
        .chain(
            iter::repeat("satisfy condition 1 but not 2").take_while(|_| {
                d -= 1;
                d > 2
            }),
        )
        .collect();
    println!("------{:?}", z);
}

(playground link)

但是,我无法评论代码的语义。如果您正在尝试查看迭代器的哪些元素“满足条件1而不是2”,那么这不是您的操作方式。您将使用std::iter::filter两次(一次使用条件1,一次使用不是条件2)来实现这一点。

© www.soinside.com 2019 - 2024. All rights reserved.