如何在for循环中跟踪先前的索引?(锈)

Cai*_*awa 2 loops rust

我想看看向量中有多少数字比前一个数字大。到目前为止,这是我的代码:

fn get_result(depths: &Vec<u32>) { 
    let mut result: Vec<u32> = Vec::new();
    for (idx,num) in depths.iter().enumerate() { 
        if depths[idx - 1] > depths[idx] { 
            result.push(depths[idx]);
    }
    
}
println!("{:?}", result);
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,它给出以下错误:

thread main panicked at 'attempt to subtract with overflow'
Run Code Online (Sandbox Code Playgroud)

我知道这是由深度 [idx - 1] 引起的,但我不完全确定如何跟踪以前的索引。

Net*_*ave 5

您还可以zip使用一些迭代器来检查对:

for (a, b) in depths.iter().zip(depths.iter().skip(1)) {
    if a < b {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)