实现说明
Ordering Then With 惰性次序以函数 main为骨架。
使用要点
- 每一步打印都带着自己的标签:
sorted:、tie resolved:、primary wins:。
常见问题
运行「Ordering Then With 惰性次序」会打印什么?
整个文件跑完,输出行以 sorted:、tie resolved:、primary wins: 这类前缀开头。
核心语句
jobs.iter().map(|job| (job.priority, job.id)).collect::<Vec<_>>()
);
代码示例
use std::cmp::Ordering;
#[derive(Debug)]
struct Job {
priority: u8,
id: u32,
}
fn main() {
let mut jobs = vec![
Job { priority: 2, id: 30 },
Job { priority: 1, id: 10 },
Job { priority: 2, id: 20 },
];
// then_with computes the tiebreak lazily, only when priorities match
jobs.sort_by(|a, b| a.priority.cmp(&b.priority).then_with(|| a.id.cmp(&b.id)));
println!(
"sorted: {:?}",
jobs.iter().map(|job| (job.priority, job.id)).collect::<Vec<_>>()
);
let tie = Ordering::Equal.then_with(|| Ordering::Less);
println!("tie resolved: {tie:?}");
println!("primary wins: {:?}", Ordering::Greater.then_with(|| Ordering::Less));
}