arrays - 在稳定 Rust 中,如何将最小值移出数组,删除其他值?

标签 arrays rust move-semantics unsafe

我有一个固定大小的数组 [T; SIZE] T 类型的值是有序的(它实现 Ord ,但不一定是 CloneDefault )。我想提取数组的最小值并删除所有其他值。
在夜间使用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 )
相关问题:
  • How do I move values out of an array one at a time?
  • 关于arrays - 在稳定 Rust 中,如何将最小值移出数组,删除其他值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63170165/

    相关文章:

    rust - 如何对数组进行排序?

    c++ - 在 std::move 之后使用对象不会导致编译错误

    c++ - 如何 move std::ostringstream 的底层字符串对象?

    c++ - 指向堆栈分配对象和 move 构造的指针

    java - 如何在jsp页面中打印java字符串数组?

    java - 搜索数组中的重复项

    java - ArrayIndexOutOfBoundsException 的原因

    javascript - 将复选框数组传递到 AJAX 调用中

    rust - 由于对 `.into_iter()` 的这种隐式调用,对向量的可变引用被移动,但调用 `.into_iter()` 显式有效

    rust - 无法从 `use` 附带的外部 crate 中找到符号