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();
Run Code Online (Sandbox Code Playgroud)
此代码创建的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();
Run Code Online (Sandbox Code Playgroud)
我知道我可以创建两个向量,然后将它们连接起来,但是效率较低。
您可以使用以下代码来了解重复的内容:
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);
}
Run Code Online (Sandbox Code Playgroud)
似乎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);
}
Run Code Online (Sandbox Code Playgroud)
不过,我无法评论您代码的语义。如果您试图查看迭代器的哪些元素“满足条件1但不满足2”,那么您将无法做到这一点。您将使用std::iter::filter
两次(条件1一次,条件2一次一次)来实现。
归档时间: |
|
查看次数: |
159 次 |
最近记录: |