rust - 如何在 Rust 中获取向量中的最小值?

标签 rust

我试图在 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/

相关文章:

rust - 如何在匹配中使用表达式作为条件?

rust - 我可以拥有既可以从切片又可以从拥有的缓冲区构造的结构吗?

rust - "Unrecognized option ' 在 Release模式下使用 rustc 编译时发布 '"

concurrency - 克隆 Arc 时会发生什么?

arrays - 沿维度求和数组

rust - 如何从 Rust 中的不安全内存创建原子

rust - Serde 结构版本检查

rust - 内存布局、对齐和释放

pointers - 是否可以匹配 Rust 中的 NULL 指针?

rust - 如何将JSON模式作为数据传递给Actix Web?