Rust のスライスまたは Vec で最大または最小の浮動小数点値のインデックスを取得する慣用的な方法は何ですか? 質問する

Rust のスライスまたは Vec で最大または最小の浮動小数点値のインデックスを取得する慣用的な方法は何ですか? 質問する

予測--Vec<f32>雌鹿ない何らかのNaN価値を持ち、何らかのNaN行動を示すことはありません。

次のサンプル セットを見てみましょう。

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

最もきれいで安定した方法は何ですか?索引上記のリストの最高値(値は負になる場合があります)ですか?

私の最初の試みは次のようなものでした。

let _tmp = *nets.iter().max_by(|i, j| i.partial_cmp(j).unwrap()).unwrap();    
let _i = nets.iter().position(|&element| element == _tmp).unwrap();

はどこにnetsありますか&Vec<f32>。これは明らかに間違っているように思えます。

動作する Python の同等物は次のとおりです (上記の仮定を考慮)。

_i = nets.index(max(nets))

ベストアンサー1

これが機能しない理由はあるのでしょうか?

>= Rust 1.62.0 (2022-06-30)

use std::cmp::Ordering;
   
fn example(nets: &Vec<f32>) {
    let index_of_max: Option<usize> = nets
        .iter()
        .enumerate()
        .max_by(|(_, a), (_, b)| a.total_cmp(b))
        .map(|(index, _)| index);
}

< Rust 1.62.0 (2022-06-30)

use std::cmp::Ordering;
   
fn example(nets: &Vec<f32>) {
    let index_of_max: Option<usize> = nets
        .iter()
        .enumerate()
        .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(Ordering::Equal))
        .map(|(index, _)| index);
}

おすすめ記事