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

标签 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);
}

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

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/

相关文章:

rust - 在 and_then 的类型定义中, T 从哪里来?

c++ - ifstream getline 问题(它只读取第一行)

java - eachWithIndex 循环不稳定

库箱中的 Rust 模块导入可见性

rust - 如何对 `cfg` 和 Cargo 使用条件编译?

rust - 错误[E0463] : can't find crate for `core` note: the `thumbv7m-none-eabi` target may not be installed

c - 是什么限制了 c 中嵌套循环的数量?

javascript - 循环和查找顺序命名输入时,自动填充监听器和 keyup 触发器上的 JQuery 语法错误

vb.net - 在 Visual Basic 中使用循环打印平方数

rust - 为什么我不能将 `&Iterator<Item = &String>` 用作迭代器?