在数组中查找具有最大属性的项 [英] Find the item in an array with the largest property

查看:42
本文介绍了在数组中查找具有最大属性的项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的结构

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?

推荐答案

使用 Iterator::max_by_key:

let a = [Point::new(1, 1), Point::new(4, 2), Point::new(2, 9)];
let max = a.iter().max_by_key(|p| p.x);

还有 Iterator::min_by_key.

另见:

这篇关于在数组中查找具有最大属性的项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆