我正在基于两个条件对向量进行排序。第一个是可以是的浮点NaN
,第二个是用于按字典顺序打断关系的字符串。
vec.sort_by(|a, b| {
match (foo(a) as f64 / bar(a) as f64).partial_cmp(&(foo(b) as f64 / bar(b) as f64)) {
Some(x) => {
Ordering::Equal => name(a).cmp(name(b)),
other => other,
}
None() => {
//Not sure what to put here.
}
}
}
foo(a)
返回int> 0,bar(a)
返回int> = 0,name(a)
返回& String
。
如何进行排序NaN
,使其大于其他任何数字,并且等于其他任何数字NaN
(字典式平局)?
你已经知道如何处理的关系,你需要的是在所期望的方式来比较浮点。只要...写出您描述的代码:
use std::cmp::Ordering;
use std::f32;
fn main() {
let mut vec = [91.0, f32::NAN, 42.0];
vec.sort_by(|&a, &b| {
match (a.is_nan(), b.is_nan()) {
(true, true) => Ordering::Equal,
(true, false) => Ordering::Greater,
(false, true) => Ordering::Less,
(false, false) => a.partial_cmp(&b).unwrap(),
}
});
println!("{:?}", vec);
}
您可能会喜欢,也可以将它包装在一个代表键的结构中:
use std::cmp::Ordering;
use std::f32;
fn main() {
let mut vec = [91.0, f32::NAN, 42.0];
vec.sort_by_key(|&a| MyNanKey(a));
println!("{:?}", vec);
}
#[derive(Debug, Copy, Clone, PartialEq)]
struct MyNanKey(f32);
impl Eq for MyNanKey {}
impl PartialOrd for MyNanKey {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for MyNanKey {
fn cmp(&self, other: &Self) -> Ordering {
match (self.0.is_nan(), other.0.is_nan()) {
(true, true) => Ordering::Equal,
(true, false) => Ordering::Greater,
(false, true) => Ordering::Less,
(false, false) => self.0.partial_cmp(&other.0).unwrap(),
}
}
}
我没有考虑过这是否适用于各种无穷大或非规范化的浮点值,因此请注意。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句