我有一个固定大小的数组 [T; SIZE]
T 类型的值是有序的(它实现 Ord
,但不一定是 Clone
或 Default
)。我想提取数组的最小值并删除所有其他值。
在夜间使用rust 中,我可以使用 array::IntoIter
为了实现这一点,但如果可能的话,我希望我的代码能够在稳定版上编译。
目前,我正在使用以下内容( playground ):
// Don't call this function if T has a custom Drop implementation or invalid bit patterns
unsafe fn get_min<T: Ord>(mut arr: [T; SIZE]) -> T {
let (idx, _) = arr.iter().enumerate().min_by(|(_, x), (_, y)| x.cmp(y)).unwrap();
unsafe { replace(&mut arr[idx], MaybeUninit::uninit().assume_init()) }
}
当然,我对此不是很满意......有没有更安全,也许不那么冗长的解决方案?
最佳答案
在 2021 版 Rust(在 Rust 1.56 及更高版本中可用)中,into_iter()
数组上的方法返回拥有项的迭代器,因此这变得简单:
fn get_min<T: Ord>(arr: [T; SIZE]) -> T {
arr.into_iter().min().unwrap() // assuming SIZE > 0
}
在 Rust 的早期版本中,您可以将最小值 move 到数组的开头,然后使用切片模式将第一个元素移出数组:fn get_min<T: Ord>(mut arr: [T; SIZE]) -> T {
for i in 1..SIZE {
if arr[i] < arr[0] {
arr.swap(0, i);
}
}
let [min, ..] = arr;
min
}
( Playground )相关问题:
关于arrays - 在稳定 Rust 中,如何将最小值移出数组,删除其他值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63170165/