I want to use max_by_key
to get the maximum value from a vector of f64
s based on a certain key. This is a simple example, with a small vector and abs
as the key:
let a: Vec<f64> = vec![-3.0, 0.2, 1.4];
*a.iter().max_by_key(|n| n.abs()).unwrap()
However, since f64
does not implement Ord
, I get
error[E0277]: the trait bound `f64: std::cmp::Ord` is not satisfied
--> src/main.rs:3:15
|
3 | *a.iter().max_by_key(|n| n.abs()).unwrap();
| ^^^^^^^^^^ the trait `std::cmp::Ord` is not implemented for `f64`
Similarly, sort_by_key
fails with the same error:
a.sort_by_key(|n| n.abs())
I know I can get around the partial ordering restriction to sort a vector of floats with sort_by
b.sort_by(|m, n| m.partial_cmp(n).unwrap_or(Less))
but that would have to be called on a vector b
for which I've computed the key (in this case abs
) for each element of a
, and then I would have to go back and find the corresponding element of a
, which seems complicated and slow. As the number of items in the list grows, I'd like to minimize passes through the data.
Are there any workarounds?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…