我正在尝试查看向量中有多少数字比前一个数字大。这是我到目前为止的代码:
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);
}
当我运行它时,它给出以下错误:
thread main panicked at 'attempt to subtract with overflow'
我知道这是由深度[idx - 1]引起的,但我不完全确定如何跟踪以前的索引。
最佳答案
您还可以使用一些迭代器zip
来检查对:
for (a, b) in depths.iter().zip(depths.iter().skip(1)) {
if a < b {
...
}
}
关于loops - 如何在for循环中跟踪先前的索引? ( rust ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70184572/