我试图在 Rust 中显示向量中的最小值,但找不到这样做的好方法。
给定一个向量 i32
:
let mut v = vec![5, 6, 8, 4, 2, 7];
我的目标是在不对它进行排序的情况下获得该向量的最小值。
在 Vec<i32>
中获取最小值的最佳方法是什么?在 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.
我发现这个 Gist 有一些用 Swift 和 Rust 表达的常见 C#/.NET Linq 操作,这很方便:https://gist.github.com/leonardo-m/6e9315a57fe9caa893472c2935e9d589
关于rust - 如何在 Rust 中获取向量中的最小值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58669865/