Using max_by_key on a vector of floats

前端 未结 1 1952
悲哀的现实
悲哀的现实 2020-12-02 02:35

I want to use max_by_key to get the maximum value from a vector of f64s based on a certain key. This is a simple example, with a small vector and <

相关标签:
1条回答
  • 2020-12-02 03:21

    If you do not want to create a wrapper type you can use the ordered_float or ord_subset crate. For example

    extern crate ordered_float;
    extern crate ord_subset;
    
    #[test]
    fn test_example_() {
        use ordered_float::OrderedFloat;
        // OrderedFloat -> NaN is greater than all other values and equal to itself.
        // NotNaN -> NotNaN::new panics if called with NaN.
    
        let mut a: Vec<f64> = vec![-3.0, 0.2, 1.4];
    
        let max = *a.iter().max_by_key(|n| OrderedFloat(n.abs())).unwrap();
        assert_eq!(-3.0, max);
    
        a.sort_by_key(|n| OrderedFloat(n.abs()));
        assert_eq!(vec![0.2, 1.4, -3.0], a);
    }
    
    #[test]
    fn test_example_ord_subset() {
        use ord_subset::OrdSubsetIterExt;
    
        let a: Vec<f64> = vec![-3.0, 0.2, 1.4];
    
        // For f64, NaN is ignored.
        let max = *a.iter().ord_subset_max_by_key(|n| n.abs()).unwrap();
        assert_eq!(-3.0, max);
    
        // ord_subset does not help with the sorting problem in the question
    }
    
    0 讨论(0)
提交回复
热议问题