在Rust中的slice或Vec中获取最大或最小浮点值的索引的惯用方式是什么? [英] What is the idiomatic way to get the index of a maximum or minimum floating point value in a slice or Vec in Rust?

查看:504
本文介绍了在Rust中的slice或Vec中获取最大或最小浮点值的索引的惯用方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设- Vec< f32> 没有任何 NaN 值或表现出任何 NaN 行为。

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

采用以下示例集:

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

获得指数的最新颖,最稳定的方法是什么(值可以为负)?

What is the neatest and most stable way to get the index of the highest value in the above list (values can be negative)?

我的最初尝试如下:

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> 。在我看来,这显然是不正确的。

Where nets is a &Vec<f32>. Which to me seems blatantly incorrect.

此功能的Python等效项(考虑到上述假设):

The Python equivalent of this that works (taking into consideration the above assumption):

_i = nets.index(max(nets))


推荐答案

我可能会做这样的事情:

I will probably do something like this:

fn main() -> Result<(), Box<std::error::Error>> {
    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(())
}

这可能是通过在Iterator上添加特征,例如使用功能 try_max_by 来实现。

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

这篇关于在Rust中的slice或Vec中获取最大或最小浮点值的索引的惯用方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆