在数组中查找具有最大属性的项 [英] Find the item in an array with the largest property
本文介绍了在数组中查找具有最大属性的项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的结构
struct Point {
pub x: i32,
pub y: i32,
}
impl Point {
fn new(x: i32, y: i32) -> Self {
Point { x, y }
}
}
还有这样的数组
[Point::new(1, 1), Point::new(4, 2), Point::new(2, 9)];
如何从该数组中提取具有最大 point.x
的项目?
How do I pull the item with largest point.x
from this array?
推荐答案
let a = [Point::new(1, 1), Point::new(4, 2), Point::new(2, 9)];
let max = a.iter().max_by_key(|p| p.x);
另见:
- 如何将 min_by_key 或 max_by_key 与对迭代期间创建的值的引用一起使用?
- 对浮点数向量使用 max_by_key
- 在 Rust 中获取切片或 Vec 中最大或最小浮点值的索引的惯用方法是什么?一个>
这篇关于在数组中查找具有最大属性的项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文