如何在 Rust 中获得向量的最小值? [英] How to get the minimum value of a vector in Rust?
问题描述
我试图在 Rust 中显示向量的最小值,但找不到好的方法.
这是我创建 i32
向量的方法:
let mut v = vec![5, 6, 8, 4, 2, 7];
我的目标是获得该向量的最小值,而无需对其进行排序.
在 Rust 中获得 i32
向量最小值的最佳方法是什么?
let minValue = vec.iter().min();匹配最小值{一些(分钟)=>println!( "最小值:{}", min ),无 =>println!( "向量为空" ),}
https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.min
<块引用>fn min(self) ->选项<Self::Item>在哪里自身::物品:秩序,
返回迭代器的最小元素.
如果几个元素同样是最小值,则返回第一个元素.如果迭代器为空,则返回 None.
我发现这个 Gist 有一些常用的 C#/.NET Linq 操作,用 Swift 和 Rust 表示,这很方便:https://gist.github.com/leonardo-m/6e9315a57fe9caa893472c2935e9d589
I'm trying to display the min value of a vector in Rust and can't find a good way to do so.
Here is how I created my vector of i32
:
let mut v = vec![5, 6, 8, 4, 2, 7];
My goal here is to get the min value of that vector without having to sort it.
What is the best way to get the min value of an i32
vector in Rust ?
let minValue = vec.iter().min();
match minValue {
Some(min) => println!( "Min value: {}", min ),
None => println!( "Vector is empty" ),
}
https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.min
fn min(self) -> Option<Self::Item> where Self::Item: Ord,
Returns the minimum element of an iterator.
If several elements are equally minimum, the first element is returned. If the iterator is empty, None is returned.
I found this Gist which has some common C#/.NET Linq operations expressed in Swift and Rust, which is handy: https://gist.github.com/leonardo-m/6e9315a57fe9caa893472c2935e9d589
这篇关于如何在 Rust 中获得向量的最小值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!