Home > Net >  How to keep track of previous index in a for loop? (rust)
How to keep track of previous index in a for loop? (rust)

Time:12-02

I'm trying to see how many numbers are bigger than the previous number in a vector. This is my code so far:

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

When I run this, it gives me the following error:

thread main panicked at 'attempt to subtract with overflow'

I know that this is caused by the depths[idx - 1], but I'm not entirely sure how to keep track of the previous index.

CodePudding user response:

You can also zip using some iterators to check the pairs:

for (a, b) in depths.iter().zip(depths.iter().skip(1)) {
    if a < b {
        ...
    }
}

CodePudding user response:

idx - 1 is invalid when idx is a usize with value 0.

You have nothing to compare to for the first element. So you should start the iteration at 1:

for idx in 1..depths.len() {
   if depths[idx - 1] > depths[idx] { 
       result.push(depths[idx]);
   }
}
  • Related