6

Based on Answer (which leads to std::cmp functions), here is the working Playground

Problem:
I try to get min / max of a Vec .
As f64 has NAN and Infinity, it doesn't fulfill Ord and complains about:

the trait `Ord` is not implemented for `f64`

How can I get the min/max anyhow for scenarios where NAN / Inf is never contained in the Vec?

til
  • 832
  • 11
  • 27

1 Answers1

14

The problem is that not all comparisons are defined - f64 is only partially ordered. Thus, it only implements PartialOrd, not Ord though. You can however provide a comparison function that just asserts that every two values are comparable. To use your custom comparison function, you would use min_by instead:

let values = vec![1.0, 0.5, 42.0];
let _ = values.into_iter().min_by(|a, b| a.partial_cmp(b).unwrap());

Keep in mind that using unwrap will panic if a and b are not comparable.

Niklas Mohrin
  • 1,756
  • 7
  • 23