如何在Rust中使用自定义比较器?

huangapple go评论63阅读模式
英文:

How to use custom comparator in Rust?

问题

I am trying to sort vector with help of custom comparator. What is the proper way to do it in Rust?

我的代码

use std::cmp::Ordering;

fn main() {
    let mut v = vec![0, -4, 1, 2, 3];
    v.sort_by(|a, b| { 
        if a.abs() < b.abs() {
            return Ordering::Less;
        }
        return  Ordering::Greater;
    });
    println!("{:?}", v);
}

我遇到了错误

error[E0599]: no method named `abs` found for reference `&{integer}` in the current scope
 --&gt; src/main.rs:6:14
  |
6 |         if a.abs() < b.abs() {
  |              ^^^ method not found in `&{integer}`
英文:

I am trying to sort vector with help of custom comparator. What is the proper way to do it in Rust?

My code

use std::cmp::Ordering;

fn main() {
    let mut v = vec![0, -4, 1, 2, 3];
    v.sort_by(|a, b| { 
        if a.abs() &lt; b.abs() {
            return Ordering::Less;
        }
        return  Ordering::Greater;
    });
    println!(&quot;{:?}&quot;, v);
}

I have an error

error[E0599]: no method named `abs` found for reference `&amp;{integer}` in the current scope
 --&gt; src/main.rs:6:14
  |
6 |         if a.abs() &lt; b.abs() {
  |              ^^^ method not found in `&amp;{integer}`

答案1

得分: 5

编译器只需要一点帮助来确定类型:添加一个类型注解

  • Vec声明处:let mut v: Vec<i32> = vec![...]
  • 或者在Vec的项上:vec![0i32, -4, 1, 2, 3]
  • 或者在闭包上:|a: &i32, b| { ... }.
英文:

The compiler just needs little help to figure the type out: add a type annotation

  • On the Vec declaration: let mut v: Vec&lt;i32&gt; = vec![...]
  • Or on the Vec's items: vec![0i32, -4, 1, 2, 3]
  • Or on the closure: |a: &amp;i32, b| { ... }.

答案2

得分: 5

Chayim 是正确的,但只是为了补充,你目前定义的排序并不是一个排序。它从不考虑相等的情况(比较 33 将导致 Ordering::Greater 的结果)。

你可以显式添加一个相等的情况,但你也可以使用 Ord::cmp 来为你执行三向比较。

let mut v: Vec<i32> = vec![0, -4, 1, 2, 3];
v.sort_by(|a, b| {
  a.abs().cmp(&b.abs())
});
英文:

Chayim is correct, but just to add on, the ordering you've defined isn't an ordering at the moment. It never has a case for equal elements (comparing 3 and 3 will result in a Ordering::Greater result).

You could add one explicitly, but you can also use Ord::cmp to do the three-way comparison for you.

let mut v: Vec&lt;i32&gt; = vec![0, -4, 1, 2, 3];
v.sort_by(|a, b| {
  a.abs().cmp(&amp;b.abs())
});

答案3

得分: 2

这可以使用 sort_by_key 来最简洁地编写。

fn main() {
    let mut v: Vec<i32> = vec![0, -4, 1, 2, 3];
    v.sort_by_key(|a| a.abs());
    println!("{:?}", v);
}
英文:

This can be written most concisely with sort_by_key.

fn main() {
    let mut v: Vec&lt;i32&gt; = vec![0, -4, 1, 2, 3];
    v.sort_by_key(|a| a.abs());
    println!(&quot;{:?}&quot;, v);
}

huangapple
  • 本文由 发表于 2023年4月20日 06:38:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76059292.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定