如何对数组进行排序? [英] How do I sort an array?

查看:63
本文介绍了如何对数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能按预期对数组进行排序?

Why cannot I not sort an array as expected?

fn main() {
    let mut a = [1,3,2];
    let s = a.sort();
    println!("{:?}", s);
}

推荐答案

a 已排序,但该方法对数组进行了就地排序.阅读 sort 的签名:sort 接受 &mut self 并返回单位(ie 没有),所以当你打印 s, 你打印 ().

a is sorted, but the method sorts the array in place. Read the signature of sort: sort takes &mut self and returns unit (i.e. nothing), so when you print s, you print ().

工作代码:

fn main() {
    let mut a = [1, 3, 2];
    a.sort();
    
    assert_eq!(a, [1, 2, 3]);
    println!("{:?}", a);
}

编写一个返回排序数组的函数

你可以写一个函数来做你想做的事:

Writing a function that returns a sorted array

You can write a function that does what you want:

fn sort<A, T>(mut array: A) -> A
where
    A: AsMut<[T]>,
    T: Ord,
{
    let slice = array.as_mut();
    slice.sort();

    array
}

fn main() {
    let a = [1, 3, 2];

    assert_eq!(sort(a), [1, 2, 3]);
}

这篇关于如何对数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆