Reverse Wrapper Flips Sort Order
Wrap keys in std::cmp::Reverse to invert ordering, turning ascending sorts into descending ones and BinaryHeap into a min-heap.
Code
use std::cmp::Reverse;
use std::collections::BinaryHeap;
fn main() {
let mut scores = vec![("ada", 91), ("bob", 84), ("cy", 91), ("dee", 77)];
// Reverse is a wrapper that flips the ordering of any Ord type
// 默认按元组升序;Reverse 把比较结果翻过来 -> 分数从高到低
scores.sort_by_key(|&(_, score)| Reverse(score));
println!("descending: {:?}", scores);
let mut min_heap = BinaryHeap::new();
for value in [5, 1, 9, 3, 7] {
min_heap.push(Reverse(value));
}
// BinaryHeap 弹出最大元素;Reverse 让"最大"变成最小值
let mut drained = Vec::new();
while let Some(Reverse(value)) = min_heap.pop() {
drained.push(value);
}
println!("min order: {:?}", drained);
}How it works
Reverse Wrapper Flips Sort Order reduces to the function main.
Repetition is confined to for value in [5, 1, 9, 3, 7] — the rest of the file is straight-line.
Using it
Running the file prints labeled results such as descending:, min order: — each operation’s effect is visible in the output.
Key statements
while let Some(Reverse(value)) = min_heap.pop() {
drained.push(value);
}
Interactive Tools for This Topic
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Reverse Wrapper Flips Sort Order print when run?
- Execute the whole file; each printed line is prefixed with a label like `descending:`, `min order:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.