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 2195
盖世英雄少女心
盖世英雄少女心 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:42

    You can find the maximum value with the following:

    let mut max_value = my_vec.iter().fold(0.0f32, |max, &val| if val > max{ val } else{ max });
    

    After finding max_value you can track its position in the vector itself:

    let index = my_vec.iter().position(|&r| r == max_value).unwrap();
    

    To get this result you need to iterate twice over the same vector. To improve the performance, you can return the index value with the max value as tuple in the fold iteration.

    Playground

提交回复
热议问题