是否可以串联迭代器?

时间:2019-04-10 22:24:24

标签: rust iterator

x = f(x)
x = f(x)
x = f(x)
x = f(x)

此代码创建一个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等于不遵守条件1的次数。

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

代码应类似于以下内容:

m

我知道我可以创建两个向量,然后将它们串联起来,但是效率较低。

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

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();

1 个答案:

答案 0 :(得分: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下)来实现该目标。