I can use the std::collections::BinaryHeap
to iterate over a collection of a struct in the greatest to least order with pop
, but my goal is to iterate over the collection from least to greatest.
I have succeeded by reversing the Ord
implementation:
impl Ord for Item {
fn cmp(&self, other: &Self) -> Ordering {
match self.offset {
b if b > other.offset => Ordering::Less,
b if b < other.offset => Ordering::Greater,
b if b == other.offset => Ordering::Equal,
_ => Ordering::Equal, // ?not sure why compiler needs this
}
}
}
Now the BinaryHeap
returns the Item
s in least to greatest. Seeing as how this is not the intended API, is this an incorrect or error prone pattern?
I realize that a LinkedList
would give me the pop_front
method, but I would need to sort the list on insert. Is that the better solution?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…