How do I get the minimum or maximum value of an iterator containing floating point numbers?

前端 未结 3 538
悲哀的现实
悲哀的现实 2020-12-11 03:54

I understand why the floats don\'t have an implementation for Ord but that doesn\'t particularly help me when I want to be lazy and use iterators.

Is there a workaro

3条回答
  •  无人及你
    2020-12-11 04:30

    Perhaps like this?

    fn main() {
        use std::cmp::Ordering;
        let mut x = [2.0, 1.0, -10.0, 5.0];
        x.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
        println!("min in x: {:?}", x);
    }
    

    One thing I struggled with is that sort_by mutates the vector in place so you can't use it in a chain directly.

提交回复
热议问题