What is the idiomatic way to get the index of a maximum or minimum floating point value in a slice or Vec in Rust?

前端 未结 5 2193
盖世英雄少女心
盖世英雄少女心 2021-01-18 03:09

Assumption -- The Vec does not have any NaN values or exhibit any NaN behavior.

T

5条回答
  •  不要未来只要你来
    2021-01-18 03:56

    I will probably do something like this:

    fn main() -> Result<(), Box> {
        let samples = vec![
            0.28, 0.3102, 0.9856, 0.3679, 0.3697, 0.46, 0.4311, 0.9781, 0.9891, 0.5052, 0.9173, 0.932,
            0.8365, 0.5822, 0.9981, 0.9977,
        ];
    
        // Use enumerate to get the index
        let mut iter = samples.iter().enumerate();
        // we get the first entry
        let init = iter.next().ok_or("Need at least one input")?;
        // we process the rest
        let result = iter.try_fold(init, |acc, x| {
            // return None if x is NaN
            let cmp = x.1.partial_cmp(acc.1)?;
            // if x is greater the acc
            let max = if let std::cmp::Ordering::Greater = cmp {
                x
            } else {
                acc
            };
            Some(max)
        });
        println!("{:?}", result);
    
        Ok(())
    }
    

    This could be implemented by adding a trait on Iterator with for example the function try_max_by.

提交回复
热议问题