更新时间:2022-11-14 08:12:03
来自@David A 的方法很酷,但如上所述,有一个陷阱: f32
& f64
不实现 Ord :: cmp
。 (这在您所知的地方确实很痛苦。)
The approach from @David A is cool, but as mentioned, there's a catch: f32
& f64
do not implement Ord::cmp
. (Which is really a pain in your-know-where.)
有多种解决方法:您可以实现 cmp
自己,也可以使用 ordered-float
等。
There are multiple ways of solving that: You can implement cmp
yourself, or you can use ordered-float
, etc..
是更大项目的一部分,我们在使用外部软件包时非常小心。此外,我很确定我们没有任何 NaN
值。因此,我宁愿使用 fold
,如果您仔细查看 max_by_key
源代码,它们就是它们的意思。
In my case, this is a part of a bigger project and we are very careful about using external packages. Besides, I am pretty sure we don't have any NaN
values. Therefore I would prefer using fold
, which, if you take a close look at the max_by_key
source code, is what they have been using too.
for (i, row) in matrix.axis_iter(Axis(1)).enumerate() {
let (max_idx, max_val) =
row.iter()
.enumerate()
.fold((0, row[0]), |(idx_max, val_max), (idx, val)| {
if &val_max > val {
(idx_max, val_max)
} else {
(idx, *val)
}
});
}