英文:
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
--> 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() < b.abs() {
return Ordering::Less;
}
return Ordering::Greater;
});
println!("{:?}", v);
}
I have an error
error[E0599]: no method named `abs` found for reference `&{integer}` in the current scope
--> src/main.rs:6:14
|
6 | if a.abs() < b.abs() {
| ^^^ method not found in `&{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<i32> = vec![...]
- Or on the
Vec
's items:vec![0i32, -4, 1, 2, 3]
- Or on the closure:
|a: &i32, b| { ... }
.
答案2
得分: 5
Chayim 是正确的,但只是为了补充,你目前定义的排序并不是一个排序。它从不考虑相等的情况(比较 3
和 3
将导致 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<i32> = vec![0, -4, 1, 2, 3];
v.sort_by(|a, b| {
a.abs().cmp(&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<i32> = vec![0, -4, 1, 2, 3];
v.sort_by_key(|a| a.abs());
println!("{:?}", v);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论