use std::iter::Iterator;
// 定义结构体
struct Point {
x: f64,
y: f64,
}
// 自定义迭代器扩展方法
trait PointIterExt: Iterator<Item = Point> {
fn filter_by_y(&mut self, threshold: f64) -> impl Iterator<Item = Point> {
self.filter(move |point| point.y > threshold)
}
fn calculate_distance(&mut self) -> impl Iterator<Item = f64> {
self.map(|point| (point.x.powi(2) + point.y.powi(2)).sqrt())
}
fn group_by_distance(&mut self) -> Vec<Vec<f64>> {
let mut groups = Vec::new();
for distance in self {
let group_index = (distance / 1.0) as usize;
if group_index >= groups.len() {
groups.resize(group_index + 1, Vec::new());
}
groups[group_index].push(distance);
}
groups
}
}
impl<I: Iterator<Item = Point>> PointIterExt for I {}
fn main() {
let points: Vec<Point> = vec![
Point { x: 1.0, y: 1.0 },
Point { x: 2.0, y: 2.0 },
Point { x: 0.5, y: 0.5 },
Point { x: 1.5, y: 0.8 },
];
let threshold = 1.0;
let result = points.iter()
.cloned()
.sorted_by_key(|point| point.x)
.filter_by_y(threshold)
.calculate_distance()
.group_by_distance();
println!("{:?}", result);
}