在浮点数向量上使用max_by_key [英] Using max_by_key on a vector of floats
问题描述
我想使用 max_by_key
根据某个键从 f64
的矢量中获取最大值。这是一个简单的例子,一个小向量和 abs
作为关键:
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()
但是,由于 f64
未实现 Ord
,我得到
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`
类似地, sort_by_key
失败并出现同样的错误:
Similarly, sort_by_key
fails with the same error:
a.sort_by_key(|n| n.abs())
我知道我可以得到围绕部分排序限制,用 sort_by
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))
但是我必须在向量 b
上调用它,我已经计算了密钥(在这种情况下 abs
)对于 a
的每个元素,然后我必须返回并找到 a
的相应元素,似乎复杂而缓慢。随着列表中项目数量的增加,我希望最大限度地减少数据传递。
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.
是否有任何变通办法?
推荐答案
如果您不想创建包装类型,可以使用 ordered_float 或 ord_subset 包。例如
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
}
这篇关于在浮点数向量上使用max_by_key的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!