如何使用1以外的步骤迭代Rust中的范围?我来自C++背景,所以我想做点什么
for(auto i = 0; i <= n; i+=2) {
//...
}
Run Code Online (Sandbox Code Playgroud)
在Rust中我需要使用该range函数,并且似乎没有第三个参数可用于自定义步骤.我怎么能做到这一点?
我想.unique()在迭代器上定义一个方法,使我能够迭代而不重复.
use std::collections::HashSet;
struct UniqueState<'a> {
seen: HashSet<String>,
underlying: &'a mut Iterator<Item = String>,
}
trait Unique {
fn unique(&mut self) -> UniqueState;
}
impl Unique for Iterator<Item = String> {
fn unique(&mut self) -> UniqueState {
UniqueState {
seen: HashSet::new(),
underlying: self,
}
}
}
impl<'a> Iterator for UniqueState<'a> {
type Item = String;
fn next(&mut self) -> Option<String> {
while let Some(x) = self.underlying.next() {
if !self.seen.contains(&x) {
self.seen.insert(x.clone());
return Some(x);
}
}
None
}
} …Run Code Online (Sandbox Code Playgroud) 在 C 语言家族中,我可以在一行中做到这一点:
for(int i = lo, int j = mid+1; i <= mid && j <= hi; i++, j++){
...
}
Run Code Online (Sandbox Code Playgroud)
但是在 Rust 中……我只能这样写:
for i in lo..mid+1 {
let mut j = mid+1;
if j <= hi {
break;
}
...
j += 1;
}
Run Code Online (Sandbox Code Playgroud)
有没有更有效的方法来实现这一点?
使用迭代器适用于上述情况,但使用迭代器会使某些场合使用算术变得麻烦,例如
for i in lo..mid+1 {
let mut j = mid+1;
if j <= hi {
break;
}
...
j += 1;
}
Run Code Online (Sandbox Code Playgroud)
在 Rust 中,这不起作用。变量i不会增加 5,而是增加 1:
for i …Run Code Online (Sandbox Code Playgroud)