Assumption--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

要获得上述列表中最高值的index(值可能为负值),最简洁、最稳定的方法是什么?

我最初的try 大致如下:

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

推荐答案

我可能会这样做:

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

这可以通过在迭代器上添加一个trait来实现,例如函数try_max_by.

Rust相关问答推荐

为什么函数不接受选项T参数的所有权?

在actix—web中使用Redirect或NamedFile响应

如何将元素添加到向量并返回对该元素的引用?

如何删除Mac Tauri上的停靠图标?

使用Box优化可选的已知长度数组的内存分配

`Pin`有没有不涉及不安全代码的目的?

在Rust中判断编译时是否无法访问

了解Rust';s特征对象和不同函数签名中的生存期注释

如何轮询 Pin>?

处理带有panic 的 Err 时,匹配臂具有不兼容的类型

如何强制匹配的返回类型为()?

从 rust 函数返回 &HashMap

`use` 和 `crate` 关键字在 Rust 项目中效果不佳

‘&T as *const T as *mut T’ 在 ‘static mut’ 项目中合适吗?

如何在 Rust 的 Hyper 异步闭包中从外部范围正确读取字符串值

使用自定义 struct 收集 Vec

试图理解 Rust 中的可变闭包

Rust,使用枚举从 HashMap 获取值

如何制作具有关联类型的特征的类型擦除版本?

如何阅读 HttpRequest 主体