rust-cookbook
rust-cookbook copied to clipboard
Sort a Vector of Floats - total_cmp vs. partial_cmp
trafficstars
In Sort a Vector of Floats partial_cmp is used, which panics with NaN.
For cases where a vector of floats can contain NaNs there is total_cmp (since Rust 1.64?)
let mut vec = vec![1.1, 1.15, 5.5, 1.123, 2.0, f32::NAN];
vec.sort_by(|a, b| a.total_cmp(b));
assert_eq!(vec[0..5], vec![1.1, 1.123, 1.15, 2.0, 5.5]);
I don't know whether partial_cmp would be preferable if there aren't any NaN.